【问题标题】:Trying to use ref inside a Vue single file component. Got undefined尝试在 Vue 单文件组件中使用 ref。未定义
【发布时间】:2019-08-15 22:10:47
【问题描述】:

我从 vuejs 开始,我试图弄清楚在根实例中引用子组件实例可以做些什么。我使用了 ref 属性,它工作得很好,除非我在单个文件组件中使用它(在模板标签中)。在这种特定情况下,我得到“未定义”。

所以,我试图理解原因,因为它对于建立动态引用非常有用。我可能很容易绕过这种情况,但我想了解问题而不是逃跑。

所以如果有人有想法;)

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

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

这是我的文件:

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.html 正文

<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 tag) 和 ref2 (app-button tag) 都找到了。但是 ref3 (在我的单个文件组件中)是未定义的。还有

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

【问题讨论】:

    标签: vue.js components undefined ref vue-directives


    【解决方案1】:

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

    如果您尝试将console.log(this.$refs.ref3); 转换为来自appButton.vue 的方法,它将起作用。但它在父级中不起作用。

    如果要从父级访问该引用,则需要使用$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 不应该是一个好习惯。

    【讨论】:

    • 啊,谢谢。所以这是不可能的,如果我想获取所有应用按钮实例的引用,我必须在 index.html 中的每个 ref 中写下我自己?
    • 是的,但你为什么要做这样的事情?
    • 它在我给出的示例中不可见,但我有几个应用程序部分组件将用作单击应用程序按钮的模式。所以我需要参考每个部分。但是我发现 this.$root.$children 里面有我想要的所有引用,所以没关系!
    猜你喜欢
    • 2017-07-20
    • 2018-10-09
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多