
[英]Vue.js: "TypeError: Cannot read properties of undefined (reading '$refs)'"
[英]Cannot read properties of undefined (reading '$refs') vue js
获取错误Cannot read properties of undefined (reading '$refs')虽然我在模板中有一个引用。 这是否意味着我必须使用 Vue 挂载钩子?
<div class="input-wrapper">
<input type="text" id="phone" placeholder="(555) 555-5555" ref="input"/>
</div>
<script>
this.$refs.input.addEventListener('input', function () {
// some code
});
</script>
在 Vue 组件的<script>
根目录中,在 Vue 2 和 Vue 3 中, this
是undefined
的:
<script>
console.log(this) // undefined
</script>
看这里。
Vue模板引用只能在组件挂载之后和卸载之前发生的任何挂钩或方法中访问。
这意味着您最早可以引用this.$refs
是在mounted中。 最新的是在beforeUnmount中。 您还可以在这两个时刻之间发生的任何钩子或方法中访问它们。
考虑到您正在尝试向 HTMLInputElement 添加事件侦听器,我建议使用v-on指令,它会在装载时自动添加事件侦听器并在卸载时将其删除。
在你的情况下:
<template>
<div class="input-wrapper">
<input
type="text"
id="phone"
placeholder="(555) 555-5555"
@input="myFn" />
</div>
</template>
<script>
export default {
methods: {
myFn(event) {
console.log(event)
}
}
}
</script>
作为旁注,您应该知道常规函数的this
无法访问组件上下文,除非它是箭头 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
*/
})
}
}
而在任何方法中(例如:上面的myFn
), this
是组件上下文,它可以访问所有组件成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.