简体   繁体   English

无法访问组件方法中的 $refs

[英]Unable to access $refs in component method

I am trying to access a ref that is defined within a template, when an element is clicked.单击元素时,我试图访问在模板中定义的引用。 Here is my HTML这是我的 HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
        <script src="https://unpkg.com/axios@0.2.1/dist/axios.min.js"></script>
    </head>
    <body>
        <div id="app">
            <site-nav></site-nav>
        </div>
        <script src="js/vjs.js"></script>
    </body>
</html>

And here is my Vue code这是我的 Vue 代码

var siteNav = Vue.component("site-nav", {
    template: `<div v-on:click="testMethod">Click me</div>
    <div ref="testref"></div>`,
    methods: {
        testMethod: function(event) {
            console.log(self.$refs);
        },
    },
});


var app = new Vue({
    el: "#app",
});

When clicking the "Click me" element, the console logs show that the $refs of the component element are inaccessible.单击“单击我”元素时,控制台日志显示组件元素的$refs不可访问。 I think this might be occurring because of a scope issue, or because the methods aren't seeing the refs before they get rendered.我认为这可能是由于 scope 问题而发生的,或者是因为这些方法在呈现之前没有看到引用。

What's going on here?这里发生了什么? I know I'm missing something simple.我知道我错过了一些简单的东西。 Thanks!谢谢!

In vue 2 you should wrap your component template by one root element (html or Vue component) like:在 vue 2 中,你应该用一个根元素(html 或 Vue 组件)包裹你的组件模板,例如:

var siteNav = Vue.component("site-nav", {
    template: `<div><div v-on:click="testMethod">Click me</div>
    <div ref="testref"></div></div>`,
   
});

then access the $refs using this which refers to component instance:然后使用引用组件实例的this访问$refs

console.log(this.$refs);

 var siteNav = Vue.component("site-nav", { template: `<div><div v-on:click="testMethod">Click me</div> <div ref="testref">test</div></div>`, methods: { testMethod: function(event) { console.log(this.$refs.testref); }, }, }); var app = new Vue({ el: "#app", });
 <html lang="en"> <head> <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script> <script src="https://unpkg.com/axios@0.2.1/dist/axios.min.js"></script> </head> <body> <div id="app"> <site-nav></site-nav> </div> <script src="js/vjs.js"></script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM