上下文
在Vue 2.0中,文档和其他文档清楚地表明,从父母到孩子的交流是通过道具进行的。
问题
父母如何通过道具告诉孩子事件发生了?
我该看个道具节目吗?这感觉不对,替代方法也是如此($emit/$on用于从子到父,而hub模型用于远程元素)。
例子
我有一个父容器,它需要告诉它的子容器,它可以在API上进行某些操作。我需要能够触发函数。
上下文
在Vue 2.0中,文档和其他文档清楚地表明,从父母到孩子的交流是通过道具进行的。
问题
父母如何通过道具告诉孩子事件发生了?
我该看个道具节目吗?这感觉不对,替代方法也是如此($emit/$on用于从子到父,而hub模型用于远程元素)。
例子
我有一个父容器,它需要告诉它的子容器,它可以在API上进行某些操作。我需要能够触发函数。
当前回答
您可以通过切换父节点中的布尔道具来模拟向子节点发送事件。
父代码:
...
<child :event="event">
...
export default {
data() {
event: false
},
methods: {
simulateEmitEventToChild() {
this.event = !this.event;
},
handleExample() {
this.simulateEmitEventToChild();
}
}
}
子代码:
export default {
props: {
event: {
type: Boolean
}
},
watch: {
event: function(value) {
console.log("parent event");
}
}
}
其他回答
您可以通过切换父节点中的布尔道具来模拟向子节点发送事件。
父代码:
...
<child :event="event">
...
export default {
data() {
event: false
},
methods: {
simulateEmitEventToChild() {
this.event = !this.event;
},
handleExample() {
this.simulateEmitEventToChild();
}
}
}
子代码:
export default {
props: {
event: {
type: Boolean
}
},
watch: {
event: function(value) {
console.log("parent event");
}
}
}
在父组件中调用子组件
<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>
在子组件中
mycomp.vue
methods:{
alertme(){
alert("alert")
}
}
您可以使用key重新加载使用key的子组件
<component :is="child1" :filter="filter" :key="componentKey"></component>
如果要重新加载带有新过滤器的组件,如果按钮单击过滤子组件
reloadData() {
this.filter = ['filter1','filter2']
this.componentKey += 1;
},
并使用过滤器来触发该函数
下面的例子是不言自明的。引用和事件可用于从父类和子类调用函数。
// 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>
在子组件上调用方法的一种简单的解耦方法是从子组件发出处理程序,然后从父组件调用它。
var Child = { template: '<div>{{value}}</div>', 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) } } }) <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <div id="app"> <my-component @handler="setValueHandler"></my-component> <button @click="click">Click</button> </div>
父处理程序在必要时跟踪子处理程序函数和调用。