How to call function on child component on parent events

后端 未结 9 1143
陌清茗
陌清茗 2020-11-27 09:16

Context

In Vue 2.0 the documentation and others clearly indicate that communication from parent to child happens via props.

Question

How does a p

9条回答
  •  旧时难觅i
    2020-11-27 10:09

    A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.

    var Child = {
      template: '
    {{value}}
    ', data: function () { return { value: 0 }; }, methods: { setValue(value) { this.value = value; } }, created() { this.$emit('handler', this.setValue); } } new Vue({ el: '#app', components: { 'my-component': Child }, methods: { setValueHandler(fn) { this.setter = fn }, click() { this.setter(70) } } })
    
    
    

    The parent keeps track of the child handler functions and calls whenever necessary.

提交回复
热议问题