Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...