Vue - 使用 ref 访问嵌套的孩子

Vue - access nested childs using ref

我有自己内部使用的 vue 组件 - 数据可以有带子元素的数组,我使用这个数组在循环中渲染它们,并根据嵌套级别在下一级、下一级等。

现在我想从 parent 运行 child 方法,然后 - 如果语句没问题,也将它调用到 child,下一级等

我用

    <mycomponent
            ref="myFirstLevelRefName"
            (...)
    ></mycomponent>

然后:

this.$refs.myFirstLevelRefName 

调用 first-level child。但是 child 个节点呢?我以这种方式使用它们:

    <mycomponent
            v-for="(subElement, index) in getSubelements()"
            ref="???"
            v-bind:data="subElement"
            v-bind:key="index"
    ></mycomponent>

我尝试将 this.$refs 从 child 级别发送到控制台,但它是空的。

如何在嵌套元素中设置 ref 名称,然后从 parent 中调用它们?

虽然技术上可以访问 $refs 嵌套子级...

Vue.component('mycomponent', {
    template: "#mycomponent",
});

new Vue({
  el: '#app',
  mounted() {
    console.log(
      'Second level <input>\'s value:',
      this.$refs.myFirstLevelRefName.$refs.mySecondLevelRefName.value
    )
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<template id="mycomponent">
    <div>
        <input ref="mySecondLevelRefName" value="Hello">
    </div>
</template>

<div id="app">
  <mycomponent ref="myFirstLevelRefName"></mycomponent>
</div>

对于简单场景,执行 parent/deep 子级或深度 ancestor/sibling 通信的一种方法是使用 事件中心 。 (复杂场景见Vuex。)

您将创建一个全局变量:

var eventHub = new Vue(); // use a Vue instance as event hub

要发出您将在任何组件中使用的事件:

eventHub.$emit('myevent', 'some value');

然后,您将在任何其他组件中收听该事件。该事件的动作可以是任何东西,包括 方法调用 (这就是您想要的):

eventHub.$on('myevent', (e) => {
    console.log('myevent received', e)
    // this.callSomeMethod();
});

演示:

var eventHub = new Vue(); // use a Vue instance as event hub

Vue.component('component-first', {
    template: "#component-1st",
    methods: {
      myMethod() {
        eventHub.$emit('myevent', 'some value');
      }
    }
});
Vue.component('component-second', {template: "#component-2nd"});
Vue.component('component-third', {
  template: "#component-3rd",
  created() {
    eventHub.$on('myevent', (e) => {
      this.check();
    });
  },
  methods: {
    check() {
      console.log('check method called at 3rd level child');
    }
  }
})

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<template id="component-1st">
    <div>
        1st level component
        <button @click="myMethod">Trigger event at 1st level component that will call 3rd level child's method</button>
        <hr>
        <component-second></component-second>
    </div>
</template>
<template id="component-2nd">
    <div>
        <component-third></component-third>
    </div>
</template>
<template id="component-3rd">
    <div><h1>3rd level child</h1></div>
</template>

<div id="app">
  <component-first></component-first>
</div>

注意:如果创建专用实例作为事件中心在您的环境中比较复杂,您可以将 eventHub 替换为 this.$root(在您的组件内) 并使用您自己的 Vue 实例作为中心。