search

Home  >  Q&A  >  body text

Vue js: Troubleshooting - Reading '$refs' property of undefined

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粉848442185P粉848442185382 days ago740

reply all(1)I'll reply

  • P粉752290033

    P粉7522900332023-11-08 13:08:12

    In the Vue component

    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.

    reply
    0
  • Cancelreply