vue3数组V-for中动态生成$refs
在项目实际需求中,可能会遇到使用数组动态生成$refs,根据官方参考,采用了以下方式实现
<template>
<div class="content">
<ul v-for="(item, index) in editableTabs" :key="item.name">
<li :id="item.name" :ref="(el) => setRef(el, index)" >
内容:{{ item.content }}
</li>
</ul>
</div>
</template>
<script setup>
import { onUnmounted, ref} from "vue";
const boxRefs = ref([]);
const setRef = (el, index) => {
console.log(el);
if (el) {
boxRefs.value[index] = el;
} else {
//如果li移除时找到对应的下标移除
// if (removeIndex.value > -1) {
// boxRefs.value.splice(removeIndex.value, 1);
// }
}
};
//移除时候的索引值
let removeIndex = ref("-1");
const editableTabs = ref([
{
title: "Tab 1",
name: "1",
content: "Tab 1 content",
},
{
title: "Tab 2",
name: "2",
content: "Tab 2 content",
},
{
title: "Tab 3",
name: "3",
content: "Tab 1 content",
},
{
title: "Tab 4",
name: "4",
content: "Tab 2 content",
},
]);
onUnmounted(() => {
console.log(boxRefs.value);
});
</script>
<style>
.content {
display: flex;
flex-direction: row;
width: 1200px;
}
</style>