以上,在v-for中,如何保证点击事件和变量只对当前div生效
如果你在 v-for
中使用点击事件和变量,并希望只对当前的 div 生效,你可以将 isShowing
变量设置为一个对象,其键是每个 item 的唯一标识符,值是布尔类型表示是否显示。以下是修改后的代码示例:
<template>
<div v-for="(item, index) in items" :key="index">
<ul>
<i class="iconfont icon-jichushezhi" @click="toggleShow(index)"></i>
<n-ellipsis style="max-width: calc(100% - 30px);">{{ item.chartname }}</n-ellipsis>
</ul>
<ul v-show="isShowing[index]" class="dropdown-menu">
<!-- Dropdown menu content -->
</ul>
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
const items = reactive([
// Your items here
]);
const isShowing = reactive({});
const toggleShow = (index: number) => {
if (isShowing[index]) {
isShowing[index] = !isShowing[index];
} else {
isShowing[index] = true;
}
};
</script>
在这个例子中,我们为每一个 item 创建了一个独立的显示状态,这样就能保证每一个 div 的显示状态是独立的。当点击某个图标时,只会切换该项的显示状态。