事件在父,事件传给子组件
时间: 2023-07-14 10:59:55 浏览: 33
如果你希望在父组件中触发事件,并将事件传递给子组件,可以使用Vue 3中的自定义事件。
在父组件中,你可以通过`$emit`方法触发一个自定义事件,并传递参数给子组件。子组件可以通过`$on`方法监听这个事件,并获取传递的参数。
下面是一个示例:
```vue
<template>
<div>
<button @click="triggerEvent">触发事件</button>
<child-component @custom-event="handleCustomEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
triggerEvent() {
const eventData = 'Hello from parent component';
this.$emit('custom-event', eventData);
},
handleCustomEvent(payload) {
// 在父组件中处理子组件触发的自定义事件
console.log(payload);
}
}
};
</script>
```
在子组件中,你可以通过`$on`方法监听父组件触发的自定义事件,并接收传递的参数。
```vue
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
};
},
mounted() {
this.$parent.$on('custom-event', this.handleCustomEvent);
},
beforeUnmount() {
this.$parent.$off('custom-event', this.handleCustomEvent);
},
methods: {
handleCustomEvent(payload) {
// 在子组件中处理父组件触发的自定义事件
this.message = payload;
}
}
};
</script>
```
在子组件中,通过`$parent`可以访问父组件的实例,从而使用`$on`方法监听父组件触发的自定义事件,并在`handleCustomEvent`方法中处理事件。
这样,当你在父组件中点击按钮触发事件时,子组件就会接收到传递的参数,并在页面中显示出来。
希望以上示例能够帮助到你!
相关推荐
![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)