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>
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:
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:And in any method (for example:
myFn
above),this
is the component context, which can access all component members.