Heim  >  Fragen und Antworten  >  Hauptteil

Vue js: Fehlerbehebung – Lesen der Eigenschaft „$refs“ von undefiniert

Es wird ein Fehler angezeigt Die Eigenschaft von undefiniert kann nicht gelesen werden (liest „$refs“) obwohl ich eine Referenz in der Vorlage habe. Bedeutet das, dass ich Vue-Montagehaken verwenden muss?

<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 Tage vor712

Antworte allen(1)Ich werde antworten

  • P粉752290033

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

    在 Vue 组件的

    查看此处。。 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 是组件上下文,它可以访问所有组件成员。

    Antwort
    0
  • StornierenAntwort