Vue js: Troubleshooting - Reading '$refs' property of undefined
P粉848442185
P粉848442185 2023-11-07 23:34:12
0
1
739

Received error Cannot read property of undefined (reading '$refs') Even though I have a reference in the template. Does this mean I have to use Vue mount hooks?

<div class="input-wrapper">
   <input type="text" id="phone" placeholder="(555) 555-5555" ref="input"/>
</div>
                            
<script>                   
  this.$refs.input.addEventLis tener('input', function () {
        // some code
 });
</script>


P粉848442185
P粉848442185

reply all(1)
P粉752290033

In the Vue component 的根内部,在 Vue 2 和 Vue 3 中,this未定义


Viewhere. . p>


Vue Template reference Can only be accessed within any hook or method that occurs after the component is installed and before it is uninstalled.

This means that the earliest you can reference this.$refs is at installed. Latest is located beforeUnmount . You can also access them in any hooks or methods that happen between those two moments.


Considering that you are trying to add an event listener to the HTMLInputElement, I recommend using the v-on directive, which will automatically add the event listener on mount and remove it on unmount delete.

In your case:


                            
sssccc

By the way, you should know that this of a regular function does not have access to the component context unless it is an arrow function:

export default {
  mounted() {
    this.$refs.input.addEventListener('input', function() {
      /*
       * Here `this` is the context of the current function, you can't 
       * access methods, computed, data or props of the component.
       * You'd need to make it an arrow function to access the component scope
       */
    })
  }
}

And in any method (for example: myFn above), this is the component context, which can access all component members.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template