【问题标题】:VueJS - trigger child functionVueJS - 触发子函数
【发布时间】:2017-06-11 03:17:36
【问题描述】:

我是使用 vuejs (2.0) 的新手。我正在尝试降低此功能:

  • 点击一个按钮
  • 子组件中的触发函数
  • 孩子数据中的增量数字

这是我目前拥有的

HTML:

<div id="root">
    <cart @addtocart="add()"></cart>
    <button @click="$emit('addtocart')">Add to Cart</button>
</div>

JS:

Vue.component('cart', {
  template: `<span>{{ items }}</span>`,
  data() {
    return {
      items: 0
    }
  },
  methods: {
    add() {
      alert('add');
    }
  }
});


new Vue({
  el: '#root',
  components: ['cart'],
});

任何帮助将不胜感激。谢谢大家!

【问题讨论】:

    标签: javascript components vue.js


    【解决方案1】:

    它非常适合在Parent Vue Component 上使用$children 访问method,它使事情变得非常简单:

    <div id="main-component">
    
       <!-- BUTTON on Main Component that will trigger the method in Child Component -->
       <button @click="$children[0].coolMethod();">I will trigger the a method on Child Component</button>
    
       <!-- CHILD Component -->
       <some-component-that-has-cool-method></some-component-that-has-cool-method>
    </div>
    

    注意:$children[0],因为我们指的是method,即index 0

    还有其他方法可以实现这一点,它们被描述为here

    以下是该讨论的摘录:

    就像一个组件的 $parent 是一个子组件 另一个,有一个孩子($children?不太记得)的 子组件,但您可以在组件中添加一个 ref 来制作 也许更清楚一点。

    祝你好运……

    【讨论】:

    • $children[0] 指的是第一个子组件,而不是它的第一个方法,这使得这有点hacky和不可扩展。
    【解决方案2】:

    您可以使用集中式集线器向其发出事件(如文档 https://vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced 中所建议的那样),然后在您的子组件中侦听这些事件并对这些事件做出反应。以下是您的代码的快速更新:

    var eventHub = new Vue();
    
    Vue.component('cart', {
      template: `<span>{{ items }}</span>`,
      data() {
        return {
          items: 0
        }
      },
      created() {
        eventHub.$on('add-item', this.add)
      },
      methods: {
        add() {
          alert('add');
          this.items++;
        }
      }
    });
    
    
    new Vue({
      el: '#root',
      components: ['cart'],
      methods: {
        addToCart() {
            eventHub.$emit('add-item')
        }
      }
    });
    

    我自己刚开始使用 vue,所以我可能错了,但据我所知,让子组件依赖于特定的父组件是一个坏主意,因为它会强制子组件“耦合”到该父组件才能运行并使其不便携。不过,从子组件备份发出事件很好,因为那只是让任何人在听的人都知道发生了什么事的组件。我想您可以使用this.$parent.$on('add-item', this.method) 直接访问父级及其发出的事件,但这对我来说看起来很骇人。也许如果您的根组件和子组件始终以这种方式紧密耦合,this.$parent 就可以了。上面的“实例化一个新的 vue 实例”示例可能只是另一种方法,无需将子组件绑定到父组件,因为 Vue 实例实现了事件系统(因此暴露了 $emit、$on 方法)

    【讨论】:

    • 非常感谢。我想我错过了“中心”文档。你知道必须实例化一个 vue 实例只是为了在组件之间进行通信的原因吗?
    • 见我上面的编辑。我自己还在学习 vue,所以有人可以更好地解释这一点。
    • 不错。这通常也称为eventBus
    • 注意子组件卸载时也要删除事件监听beforeDestroy: function () { eventHub.$off('add-item', this.add) },
    猜你喜欢
    • 2018-09-29
    • 2021-11-23
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多