Vue JS组件侦听事件的孙子组件

时间:2019-02-26 14:46:36

标签: vuejs2

Vue文档(https://vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events)中有注释,但这也适用于孙子孙吗?

grandchild.vue

   <select class="form-control" v-model="selected" @change="updateValue()" >
     ...
    </select>
  methods: {
    updateValue: function () {
      this.$emit('refreshModel', this.selected)
      this.$emit('input', this.selected)
      console.log('selected ' + this.selected + ' in ' + this.$props.field)
    }
  }

Grandparent.vue

<parent-form ...
              v-on:refresh-model="refreshModel"
             ...
</parent-form>

methods: {
  refreshModel: function (event) {
    console.log("Hello Vue JS");
  },

很明显,我已经删除了很多代码,并希望只保留了要点。

运行此命令的结果是显示孙子中的log语句,而不显示refreshModel函数。

有人能看到我在做什么吗?

致谢

2 个答案:

答案 0 :(得分:1)

从 Vue 2.4 开始,有一个非常简单的方法:

  1. 孙子像以前一样发出信号。

  2. 中代中,只需添加 v-on="$listeners" ,将信号上游传递到其自己的父代。示例:

    <块引用>
    <!-- Relays the signal from its child component to its own parent -->
    <vue-grandchild-component v-on="$listeners">  
    </vue-grandchild-component>
    
  3. 祖父(最终信号目的地)中,像以前一样捕捉信号。

有关详细信息,请包含您可以运行的代码片段,请参阅 this thread

答案 1 :(得分:0)

您需要“菊花链式”连接事件,因此您必须在“父表单”中放置一个侦听器,以将事件重新发送给祖父母或外祖父母。

孩子(发射)->父母(听,发射)->祖父母(听)

Vuex通过使用“状态”作为唯一的事实来源来解决此问题,因此仅需要更新“状态”以反映所有连接组件中的变化。

https://vuex.vuejs.org/

相关问题