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

Categories

0 votes
4.1k 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/[email protected]/dist/vue.min.js"></script>
        <script src="https://unpkg.com/[email protected]/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 Answer

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/[email protected]/dist/vue.min.js"></script>
        <script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
    </head>
    <body>
        <div id="app">
            <site-nav></site-nav>
        </div>
        <script src="js/vjs.js"></script>
    </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...