首页  >  问答  >  正文

Vue js:故障排除 - 读取未定义的“$refs”属性

收到错误无法读取未定义的属性(读取“$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>


P粉848442185P粉848442185346 天前710

全部回复(1)我来回复

  • P粉752290033

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

    在 Vue 组件的

    查看此处。。 p>


    Vue 模板引用只能在发生的任何钩子或方法内访问在组件安装之后和卸载之前。

    这意味着最早您可以引用的this.$refs位于已安装最新位于 beforeUnmount 。您还可以在这两个时刻之间发生的任何挂钩或方法中访问它们。


    考虑到您正在尝试向 HTMLInputElement 添加事件侦听器,我建议使用 v-on 指令,该指令会在挂载时自动添加事件侦听器,并在卸载时将其删除。

    就您而言:

    
                                
    sssccc
    

    顺便说一句,您应该知道常规函数的 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 是组件上下文,它可以访问所有组件成员。

    回复
    0
  • 取消回复