【问题标题】:Vue JS component listens to grandchild component for eventVue JS 组件监听孙子组件的事件
【发布时间】:2019-07-20 03:35:03
【问题描述】:

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)
    }
  }

祖父母.vue

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

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

很明显,我已经删除了很多代码,希望只留下必需品。

运行的结果是显示了孙子中的日志语句,但没有显示refreshModel函数。

谁能看出我做错了什么?

问候

【问题讨论】:

    标签: vuejs2


    【解决方案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. 祖父母(最终的信号目的地)中,像以前一样捕捉信号。

    更多细节,包括一个可以运行的代码sn-p,见this thread

    【讨论】:

      【解决方案2】:

      您需要“菊花链”事件,因此您必须在 Parent-Form 中放置一个侦听器,将事件重新发送给祖父母。

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

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

      https://vuex.vuejs.org/

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 1970-01-01
        • 2019-10-15
        • 2020-06-25
        • 2015-05-07
        • 2017-02-21
        • 1970-01-01
        • 2021-06-05
        • 2019-06-04
        相关资源
        最近更新 更多