Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...