The `$refs` variable in Vue can be used to reference a specific Vue component within a class-st

Would it be possible to access this.$refs.label? I am using the package vue-property-decorator.

Below is the content of the component:

<template>
  <div>
    <label ref="label">asd</label>
  </div>
</template>

<script lang="ts">
class Someclass extends Vue {
  public $refs!: {
    label: HTMLElement
  }

  private mounted(): void {
    console.log(this.$refs.label) // returns a Vue component, instead of just html
  }
}
</script>

I believe that the issue lies in this pointing to the class itself. How can I successfully access this.$refs.label?

Answer №1

When using a ref on a Vue component, you can access its DOM element by referring to it like this:

this.$refs.label.$el

The reference this.$refs.label points to a Vue instance, and you can find more information about its properties in the official documentation here.

About the ref attribute:

The ref attribute is used to assign a reference to an element or a child component. This reference will be stored under the $refs object of the parent component. If applied to a regular DOM element, the reference will be that element; if applied to a child component, the reference will be the component instance.

Latest Information Update

It turns out that your example includes a label element instead of a component. My initial assumption was based on not having all the code provided in the question, so I referenced relevant parts of the documentation. Upon reviewing your code below, it appears that the output does not match what you described initially.

Vue.component('my-component', {
  template: '<div><label ref="label">asd</label></div>',
  
  mounted() {
    const ref = this.$refs.label;
    console.log(ref);
    console.log("typeof(ref): " + typeof(ref));
    console.log("Is component: " + (ref instanceof Vue));
    console.log("Is HTMLElement: " + (ref instanceof HTMLElement));
  }
})

new Vue({
  el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app>
  <my-component />
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite being deployed on Vercel, the process.env variables in Nextjs are still not functioning as expected

I'm currently working on a project that involves using 4 api keys that I need to keep hidden: STORYBLOK_API_KEY= EMAILJS_SERVICE_ID= EMAILJS_USER_ID= EMAILJS_TEMPLATE_ID= All of these keys are being accessed using process.env.XXX. What's inte ...

Sharing data between the main component and the sidebar in React-Router

Currently working with Meteor in combination with React-Router, and this is the code I'm dealing with: Routes.jsx: Meteor.startup(() => { render( <Router history={browserHistory}> <Route path='/' component={App}> ...

Creating a Typescript version of the mongodb project aggregation functionality

Present scenario: I am currently working on creating a type-safe wrapper for the node-mongodb driver. I am facing challenges in determining the return type for the project aggregation stage. Feel free to check out the TypeScript Playground here class Base ...

Positioning JQuery tooltips

I've been developing a simple tooltip tool (check out the fiddle link below), but I'm encountering some issues with positioning. My goal is to have the tooltip appear centered and above the clicked link, however right now it appears at the top le ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

How come Vue is returning a false value for my v-if condition even though it should be true?

After running this code, I noticed that Vue is displaying the second template even though the value of groups.length is 1. Why is this happening? Could it be related to the sequence in which mounting occurs and v-if is evaluated? I can confirm that the v ...

Deciding Between Javascript DOM and Canvas for Mobile Game Development

My idea for a mobile game involves using the Phonegap framework to create a game where players can control a ball's movement by utilizing their phone's accelerometer. I also envision incorporating other elements like enemies and walls into the ga ...

"Angular Ionic combination for displaying lists with customized headers and footers on cards

My issue is fairly straightforward - I am looking to create a list card with item array from my controller. However, I am struggling with how to structure my data in the HTML. The list card should have a header, content, and footer. I have attempted variou ...

Angular template not refreshing automatically

Within my controller: $scope.deleteUser = function(user){ $.ajax({ url: "/users/" + user.id.toString(), method: "DELETE", success: function(result){ $scope.users = result["users"]; ...

What is the secret behind the checkbox retaining its checked status upon page reload?

My dataTable is loading all data from the MySQL database and the first checkboxes are automatically incremented when a new row is added. However, users may check or uncheck these checkboxes. My goal is to retain the checkbox results even when the page is r ...

Discovering objects on a JavaScript webpage using Selenium

Looking to automate some searches for myself, but running into an issue. Here is the website in question: Struggling to locate the search bar using the program, and unsure why. driver = webdriver.Firefox() driver.get('https://shop.orgatop.de/') ...

Issue: Experiencing multiple re-renders when attempting to send a post request to the backend using

export default function CRouter() { const [token, setToken] = useLocalStorage('auth', '') const [user, setUser] = useState(false); const GetUser = () => { if (token !== "" && !user) { axios.post(&apo ...

Exploring the capabilities of incorporating multiple nested if-else statements in an AJAX/JavaScript function

Can anyone help me with this code issue? I am trying to run a function with data received from a CI controller to ajax, but having trouble with multiple if else statements. The code works fine with one if else statement, but not with nested or multiple one ...

I find that ChangeDetectionStrategy.OnPush does not function as anticipated

Exploring the performance boost of ChangeDetectionStrategy.OnPush in Angular 2 (detailed here) has been my recent focus. However, I've encountered an interesting scenario. In my code, I have the parent component AppComponent: @Component({ selector ...

Transforming JSON dates to Javascript dates using AngularJS and ASP.NET

How can I convert a JSON date /Date(1454351400000)/ into a proper date format using AngularJS and ASP.NET? $http.get('/home/GetProducts') .success(function (result) { $scope.products = result; }) .error(function (data) { ...

Using SCSS aliases in a Vue single file component with the help of Rollup

Adding an alias for SCSS files in a Vue SFC when using Webpack is straightforward. For example: <style lang="scss"> @import "~scss/config/config"; ... </style> This is how you would do it in Webpack: alias: { sass: path.resolve(__dirname, ...

When I define a type in TypeScript, it displays "any" instead

Imagine a scenario where we have a basic abstract class that represents a piece in a board game such as chess or checkers. export abstract class Piece<Tags, Move, Position = Vector2> { public constructor(public position: Position, public tags = nul ...

How can I display hardcoded array information as comments along with responses?

Currently, I am facing a challenge in displaying my hardcoded array data as comments with replies. The requirement is to achieve this within a single component file. While I have successfully managed to print the data out as a list, the desired outcome sh ...

Repeating percentages displayed in a progress bar

I created a responsive progress bar, but the progress values are repeating. I only want the central value to be displayed. Any suggestions on how to fix this issue? DEMO <div id="tab1"> <dx-data-grid class="tableTask" [dataSource]="datas" ...

The TypeScript Mongoose function is not available for type <Context = any>

How can I implement a schema method in Mongoose and TypeScript to compare passwords? interface IUser extends Document { email: string; username: string; password: string; role: string; comparePassword( candidatePassword: string, next: Nex ...