上下文

在Vue 2.0中,文档和其他文档清楚地表明,从父母到孩子的交流是通过道具进行的。

问题

父母如何通过道具告诉孩子事件发生了?

我该看个道具节目吗?这感觉不对,替代方法也是如此($emit/$on用于从子到父,而hub模型用于远程元素)。

例子

我有一个父容器,它需要告诉它的子容器,它可以在API上进行某些操作。我需要能够触发函数。


当前回答

您可以使用key重新加载使用key的子组件

<component :is="child1" :filter="filter" :key="componentKey"></component>

如果要重新加载带有新过滤器的组件,如果按钮单击过滤子组件

reloadData() {            
   this.filter = ['filter1','filter2']
   this.componentKey += 1;  
},

并使用过滤器来触发该函数

其他回答

不喜欢在创建期间在子进程中使用$on绑定的事件总线方法。为什么?随后的create调用(我使用vue-router)将消息处理程序绑定不止一次——导致每条消息有多个响应。

传统的解决方案是将道具从父母传递给孩子,并在孩子中放置一个属性监视器。唯一的问题是,孩子只能在价值转变上采取行动。多次传递相同的消息需要某种记账来强制转换,以便子进程能够接受更改。

我发现,如果我将消息包装在一个数组中,它总是会触发子监视程序——即使值保持不变。

家长:

{
   data: function() {
      msgChild: null,
   },
   methods: {
      mMessageDoIt: function() {
         this.msgChild = ['doIt'];
      }
   }   
   ...
}

孩子:

{
   props: ['msgChild'],
   watch: {
      'msgChild': function(arMsg) {
         console.log(arMsg[0]);
      }
   }
}

HTML:

<parent>
   <child v-bind="{ 'msgChild': msgChild }"></child>
</parent>

您所描述的是父进程状态的变化。你把它通过道具传递给孩子。就像你说的,你会看好那个道具。当子进程执行操作时,它会通过emit通知父进程,然后父进程可能会再次更改状态。

var Child = { template: '<div>{{counter}}</div>', props: ['canI'], data: function () { return { counter: 0 }; }, watch: { canI: function () { if (this.canI) { ++this.counter; this.$emit('increment'); } } } } new Vue({ el: '#app', components: { 'my-component': Child }, data: { childState: false }, methods: { permitChild: function () { this.childState = true; }, lockChild: function () { this.childState = false; } } }) <script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script> <div id="app"> <my-component :can-I="childState" v-on:increment="lockChild"></my-component> <button @click="permitChild">Go</button> </div>

如果您确实希望将事件传递给子节点,可以通过创建一个总线(它只是一个Vue实例)并将其作为道具传递给子节点来实现。

下面的例子是不言自明的。引用和事件可用于从父类和子类调用函数。

// PARENT
<template>
  <parent>
    <child
      @onChange="childCallBack"
      ref="childRef"
      :data="moduleData"
    />
    <button @click="callChild">Call Method in child</button>
  </parent>
</template>

<script>
export default {
  methods: {
    callChild() {
      this.$refs.childRef.childMethod('Hi from parent');
    },
    childCallBack(message) {
      console.log('message from child', message);
    }
  }
};
</script>

// CHILD
<template>
  <child>
    <button @click="callParent">Call Parent</button>
  </child>
</template>

<script>
export default {
  methods: {
    callParent() {
      this.$emit('onChange', 'hi from child');
    },
    childMethod(message) {
      console.log('message from parent', message);
    }
  }
}
</script>

我认为我们应该考虑父母使用孩子的方法的必要性。实际上,父组件不需要关心子组件的方法,而可以将子组件视为FSA(有限状态机)。父组件来控制子组件的状态。因此,观察状态变化或仅使用计算功能就足够了

在父组件中调用子组件

<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>

在子组件中

mycomp.vue

    methods:{     
    alertme(){
            alert("alert")
            }
    }