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

问题描述 投票:0回答:1

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

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

所以,如果有人有想法;)

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

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

这是我的文件:

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(标题标记)和ref2(app-button标记)。但是ref3(在我的单个文件组件中)是未定义的。也

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

vue.js components undefined ref vuejs-directive
1个回答
0
投票

您设置的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不应该是一个好习惯。

© www.soinside.com 2019 - 2024. All rights reserved.