Vue js:故障排除 - 读取未定义的“$refs”属性
P粉848442185
P粉848442185 2023-11-07 23:34:12
[Vue.js讨论组]

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

全部回复(1)
P粉752290033

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号