收到错误无法读取未定义的属性(读取“$refs”)尽管我在模板中有一个引用。这是否意味着我必须使用 Vue 挂载钩子?
<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>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在 Vue 组件的
的根内部,在 Vue 2 和 Vue 3 中,this是未定义:查看此处。。 p>
Vue 模板引用只能在发生的任何钩子或方法内访问在组件安装之后和卸载之前。
这意味着最早您可以引用的
this.$refs位于已安装。 最新位于 beforeUnmount 。您还可以在这两个时刻之间发生的任何挂钩或方法中访问它们。考虑到您正在尝试向 HTMLInputElement 添加事件侦听器,我建议使用 v-on 指令,该指令会在挂载时自动添加事件侦听器,并在卸载时将其删除。
就您而言:
顺便说一句,您应该知道常规函数的
this无法访问组件上下文,除非它是箭头函数: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是组件上下文,它可以访问所有组件成员。