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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM