vue3爷孙事件传递
时间: 2023-11-09 18:03:40 浏览: 50
在Vue3中,可以使用`emits`选项来声明一个组件可以触发的事件,然后在父组件中使用`v-on`指令监听子组件触发的事件。爷孙组件之间的事件传递可以通过在中间层组件中声明事件和监听事件来实现。
具体来说,假设有一个爷爷组件、一个父亲组件和一个孙子组件,爷爷组件通过`v-on`监听父亲组件触发的事件,父亲组件通过`v-on`监听孙子组件触发的事件,那么当孙子组件触发事件时,事件会依次向上传递到父亲组件和爷爷组件。
示例代码如下:
```html
<!-- 爷爷组件 -->
<template>
<div>
<p>我是爷爷组件</p>
<father-component @child-event="handleChildEvent"></father-component>
</div>
</template>
<script>
import FatherComponent from './FatherComponent.vue'
export default {
components: {
FatherComponent
},
methods: {
handleChildEvent() {
console.log('爷爷组件收到了孙子组件触发的事件')
}
}
}
</script>
<!-- 父亲组件 -->
<template>
<div>
<p>我是父亲组件</p>
<son-component @child-event="handleChildEvent"></son-component>
</div>
</template>
<script>
import SonComponent from './SonComponent.vue'
export default {
components: {
SonComponent
},
emits: ['child-event'],
methods: {
handleChildEvent() {
this.$emit('child-event')
}
}
}
</script>
<!-- 孙子组件 -->
<template>
<div>
<p>我是孙子组件</p>
<button @click="handleClick">触发事件</button>
</div>
</template>
<script>
export default {
emits: ['child-event'],
methods: {
handleClick() {
this.$emit('child-event')
}
}
}
</script>
```
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)