上下文
在 Vue 2.0 中,文档和 others清楚地表明 parent 与 child 之间的交流是通过 Prop 进行的。
问题
parent 如何通过 Prop 告诉 child 发生了什么事?
我应该只看一个叫做事件的 Prop 吗?这感觉不对,替代方案也不对($emit
/$on
用于子到父,hub 模型用于远距离元素)。
例子
我有一个父容器,它需要告诉它的子容器可以在 API 上执行某些操作。 我需要能够触发函数。
最佳答案
Vue 3 组合 API
创建一个 ref
对于子组件,在模板中分配它,并使用 <ref>.value
直接调用子组件。
<script setup>
import {ref} from 'vue';
const childComponentRef = ref(null);
function click() {
// `childComponentRef.value` accesses the component instance
childComponentRef.value.doSomething(2.0);
}
</script>
<template>
<div>
<child-component ref="childComponentRef" />
<button @click="click">Click me</button>
</div>
</template>
一些注意事项-
- 如果您的子组件正在使用
<script setup>
,您需要使用doSomething
声明公共(public)方法(例如上面的defineExpose
) . - 如果您使用的是 Typescript,有关如何键入注释的详细信息是 here .
Vue 3 选项 API/Vue 2
给子组件一个ref
并使用 $refs
直接在子组件上调用方法。
html:
<div id="app">
<child-component ref="childComponent"></child-component>
<button @click="click">Click</button>
</div>
JavaScript:
var ChildComponent = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
}
}
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
},
methods: {
click: function() {
this.$refs.childComponent.setValue(2.0);
}
}
})
有关详细信息,请参阅 Vue 3 docs on component refs或 Vue 2 documentation on refs .
关于javascript - 如何在父事件上调用子组件上的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632711/