SoFunction
Updated on 2025-04-04

About the use of ref in vue (this.$refs is obtained as undefined)

vue's ref(this.$refs is obtained as undefined)

If what you get is always empty, please pay attention:

1. Where did you call, and the object you call

Try calling in mounted() is effective

Does the object called exist originally, or it still appears after data rendering. Similarly, call it in mounted() to see

2. Is the call object an array list?

I set the ref on the v-for list at the beginning and directly get this.$, which is always empty.

Later I discovered that this.$ is an array and cannot get the style through .style.

Only this.$ array can be traversed and styled on this.$[index]

// Updated 6.14, this statement is a bit problematic

But like height width, you can get it by offsetHeight, etc.

3. Whether the call object is used in conjunction with v-if

Ref is not responsive, and all dynamically loaded template updates cannot change accordingly.

Solution:

pass

setTimeout(() => {

}, 0)

To get the data

Several notes on the $refs attribute of vue

1. Get dom in vue recommended to use $refs to get

But sometimes this.$ is undefined.

Scenario 1: Used in created()

During this life cycle, data observations, properties and methods are performed, and watch event callbacks are called. However, the page has not been mounted yet, there is no e l attribute, t h i s . el attribute, attribute, and dom cannot be called.

Solution: Change to using it in mounted()

Scene 2: The parent element or current element uses v-if or v-show

Because $refs is not responsive, it will only take effect after component rendering is completed and does not exist during initial rendering.

Because it is non-responsive, all dynamically loaded template updates cannot change accordingly.

Solution: It can be achieved by settingTimeout(()=>{…}, 0).

2. If using v-for

When traversing the ref, you can use :, that is, :ref ="variable" , which results in different refs.

<div v-for="(item,index) in arr" :key="index">
  <child  :ref="`refName${index}`"/>
</div>
//this.$refs[`refName${index}`] Each item is an array containing only one elementthis.$refs[`refName${index}`][0].fun();//Calling methods within the first component

However, it can also be used without using :, the ref obtained at this time will be an array containing these subcomponents of the corresponding data source.

<div v-for="(item,index) in arr" :key="index">
  <child  ref="refName"/>
</div>
//this.$ is an array containing these subcomponents corresponding to the data sourcethis.$[0].fun();//Calling methods within the first component

The above is personal experience. I hope you can give you a reference and I hope you can support me more.