简体   繁体   中英

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

<!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

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. I think this might be occurring because of a scope issue, or because the methods aren't seeing the refs before they get rendered.

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:

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:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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