子组件有传值前提下,父组件递归调用子组件,事件触发如何判断当前是哪个组件
时间: 2023-11-29 07:59:46 浏览: 45
可以在子组件中通过 $emit() 方法触发一个自定义事件,并将当前组件的标识作为参数传递给父组件。父组件在递归调用子组件的时候,可以将这个标识作为参数传递给子组件,子组件在触发自定义事件时就可以将这个标识一并传递给父组件。这样父组件就可以判断当前触发事件的是哪个子组件了。
代码示例:
子组件:
```javascript
<template>
<div>
<button @click="clickHandler">点击触发事件</button>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
id: {
type: Number,
required: true
}
},
methods: {
clickHandler() {
this.$emit('custom-event', this.id)
}
}
}
</script>
```
父组件:
```javascript
<template>
<div>
<child-component v-for="item in list" :key="item.id" :id="item.id" @custom-event="customEventHandler"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
data() {
return {
list: [
{ id: 1 },
{ id: 2 },
{ id: 3 }
]
}
},
methods: {
customEventHandler(id) {
console.log('当前触发事件的是子组件' + id)
}
}
}
</script>
```
相关推荐
![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)