尝试在 Vue 单文件组件中使用 ref。未定义

Trying to use ref inside a Vue single file component. Got undefined

我从 vuejs 开始,我试图弄清楚如何在根实例中引用 child 组件实例。我使用了 ref 属性并且它工作得很好,除非我在单个文件组件(在模板标签中)中使用它。在这种特定情况下,我得到 'undefined'.

所以,我试图理解为什么,因为它对于建立动态引用非常有用。我可能可以轻松绕过这种情况,但我想了解问题而不是 运行。

所以如果有人有想法 ;)

我正在使用 webpack 在我的 app.js 中导入我的单个文件组件并编译它。然而,模板编译不是由 webpack 完成的,而是由浏览器在 运行 时完成的(也许这是解释的开始?)。

我的应用程序非常简单,我在点击 header 时记录了我的引用,所以我认为它与生命周期回调无关。

这是我的文件:

app.js

import Vue from 'Vue';
import appButton from './appButton.vue';
import appSection from './appSection.vue';


var app = new Vue({
    el: '#app',
    components:
    {
        'app-button' : appButton
    },
    methods:
    {
        displayRefs: function()
        {
            console.log(this.$refs.ref1);
            console.log(this.$refs.ref2);
            console.log(this.$refs.ref3);
        }
    }
});

我的组件appButton.vue

<template>
    <div ref="ref3" v-bind:id="'button-'+name" class="button">{{label}}</div>
</template>


<script>

    module.exports = 
    {
        props: ['name', 'label']
    }

</script>

我的index.htmlbody

<body>

    <div id="app">

        <div id="background"></div>

        <div id="foreground">

            <img id="photo" src="./background.jpg"></img>

            <header ref="ref1">
                    <h1 v-on:click="displayRefs">My header exemple</h1>
            </header>


            <nav>
                <app-button ref="ref2" name="presentation" label="Qui sommes-nous ?"></app-button>
            </nav>

        </div>

    </div>

    <script src="./app.js"></script>

</body>

ref1(header 标签)和 ref2(app-button 标签)都找到了。但是 ref3 (在我的单个文件组件中)是未定义的。还有

感谢您给我的所有答复,希望这不是一个愚蠢的错误。

您设置的 ref 只能在组件本身中访问。

如果您尝试 console.log(this.$refs.ref3); 进入 appButton.vue 的方法,它将起作用。但它不会在父级中工作。

如果要从父级访问该 ref,则需要使用 $ref2 访问组件,然后使用 $ref3。试试这个:

var app = new Vue({
    el: '#app',
    components:
    {
        'app-button' : appButton
    },
    methods:
    {
        displayRefs: function()
        {
            console.log(this.$refs.ref1);
            console.log(this.$refs.ref2);
            console.log(this.$refs.ref2.$refs.ref3); // Here, ref3 will be defined.
        }
    }
});

从父级访问某些子级 ref 并不是一个好的做法。