父组件接受子组件传来的方法
时间: 2023-09-04 22:14:51 浏览: 48
当子组件通过事件向父组件传递方法时,父组件可以在事件监听器中接收这个方法。以下是一个示例:
父组件:
```vue
<template>
<div>
<p>父组件</p>
<ChildComponent @childMethod="parentMethod" />
<p>父组件接收到的消息:{{ message }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: ''
};
},
methods: {
parentMethod(data) {
console.log('父组件的方法被调用');
this.message = data; // 接收子组件传递过来的方法
}
}
}
</script>
```
子组件:
```vue
<template>
<div>
<p>子组件</p>
<button @click="childMethod">触发子组件方法</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
const data = 'Hello, 父组件!';
this.$emit('childMethod', data); // 触发自定义事件,传递给父组件
}
}
}
</script>
```
在父组件中,通过`@childMethod="parentMethod"`监听子组件触发的事件,并将数据传递给父组件中的`parentMethod`方法。子组件通过`this.$emit('childMethod', data)`触发自定义事件,并将数据传递给父组件。
父组件中的`parentMethod`方法接收到子组件传递过来的数据,并将其赋值给`message`,然后可以在模板中显示出来。
这样就实现了子组件向父组件传递方法并接收的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)