VUE for循环 默认选中第一条数据
for循环渲染列表默认选中第一条数据 点击其他选项切换数据
<div><div class="Subtitle" style="padding: 5px 40px;">项目清单</div><div class="project-manifest"><div v-for="(item, index) in project" :key="index" class="project-list" :class="{ active: index === selectedProjectIndex }" @click="projectFn(item.id,item.name)"><span class="num">{{ index + 1 }}</span> <span class="project-name">{{ item.name }}</span></div></div>
</div>
主要代码: :class="{ active: index === selectedProjectIndex }" 以及 @click="projectFn(item.id)"
active是样式名称 index是前面循环的index selectedProjectIndex是接下来要定义的变量
点击方法传递的就是该条数据的id
const project = ref([{ id: '1', name: '湖北省公租房管理第三方评价项目', sonTask: "8", problem: '2' },{ id: '2', name: '河北省公租房管理第三方评价项目', sonTask: "7", problem: '1' },{ id: '3', name: '河南省省公租房管理第三方评价项目', sonTask: "6", problem: '3' },
])//默认为0 就会默认选中
const selectedProjectIndex = ref(0)function projectFn(id) {//根据传递回来的id判断是哪一条数据被选中selectedProjectIndex.value = project.value.findIndex(item => item.id === id);}
最后样式 (自己定义)
.active {background: url(../../assets/visualization/background/activeBgc.png) no-repeat;background-size: 100% 100%;}