在Vue 2中,组件可以通过props接收父组件传递的数据,包括函数。这使得父组件能够将函数传递给子组件,子组件可以使用这些函数来与父组件通信。
以下是一个简单的示例,展示了如何在Vue 2组件中接收和使用props函数:
父组件 (ParentComponent.vue
):
子组件
<template>
<div>
<button @click="callParentMethod">Call Parent Method</button>
</div>
</template>
<script>
export default {
props: {
parentMethod: {
type: Function,
required: true
}
},
methods: {
callParentMethod() {
// 调用从父组件接收的方法
if (this.parentMethod) {
// 这是一个参数
this.parentMethod({id:'1'});
}
}
}
};
</script>
// 父组件
<template>
<div>
<child-component :parentMethod="parentMethod" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
parentMethod(rowData) {
// 父组件的方法被调用,参数是 rowData
console.log('This is a message from the parent component.',rowData);
}
}
};
</script>
在这个例子中,ParentComponent
定义了一个方法 parentMethod
,并将它作为 parentMethod
prop 传递给 ChildComponent
组件。ChildComponent
接收这个 prop,并在用户点击按钮时调用它。这展示了父子组件之间通过函数prop进行通信的一个简单用例