vue3中context.emit遇见的坑
作者:互联网
场景描述
今天遇见一个问题 ,子组件向上抛出去的事件。
被执行了两次,原因是 context.emit('click', item.id)
你的事件名是click
将click更改为其他事件名称,就可以去解决了
vue3中context.emit遇见的坑
<template>
<div class="table-cont">
<div
v-for="(item, index) in tabData"
:key="index"
@click="tabHanderClick(item)"
class="item-blok"
:class="{ activehengline: item.id == currentIndex }"
>
{{ item.name }}
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
props: {
tabData: {
type: Array,
default: () => {
return []
},
},
},
setup(props, context) {
let currentIndex = ref(1)
const tabHanderClick = item => {
currentIndex.value = item.id
//这里不要向外抛出click事件,可以向外抛出其他的事件。如clickHander
//这样就不会被触发两次了
context.emit('click', item.id)
}
return { tabHanderClick, currentIndex }
},
})
</script>
父组件
<template>
<div class="">
<table-list :tabData="tabData" @click="tabHanderClick"></table-list>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import tableList from '../component/table-list.vue'
export default defineComponent({
components: {
'table-list': tableList,
},
setup() {
function tabHanderClick(idIndex) {
console.log('fa==>', idIndex)
}
let tabData = [
{
name: '我的盘点',
id: 1,
},
{
name: '盘点确认',
id: 2,
},
]
return { tabHanderClick, tabData }
},
})
</script>
标签:emit,tabHanderClick,click,item,context,vue3,id,defineComponent 来源: https://www.cnblogs.com/IwishIcould/p/15479885.html