Vue js: Troubleshooting - Reading '$refs' property of undefined
P粉8484421852023-11-07 23:34:12
0
1
638
Received errorCannot 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?
VueTemplate referenceCan only be accessed within any hook or method that occurs after the component is installed and before it is uninstalled.
This means that theearliestyou can referencethis.$refsis atinstalled.Latestis locatedbeforeUnmount. 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 thev-ondirective, 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 thatthisof 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:myFnabove),thisis the component context, which can access all component members.
In the Vue component
的根内部,在 Vue 2 和 Vue 3 中,
this
是未定义
:Viewhere. . p>
VueTemplate referenceCan only be accessed within any hook or method that occurs after the component is installed and before it is uninstalled.
This means that theearliestyou can reference
this.$refs
is atinstalled.Latestis locatedbeforeUnmount. 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 thev-ondirective, 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.