单选业务:
template
<template>
<div class="a-page">
<ui>
<li
v-for="(item, index) in obj"
:key="index"
:class="{ active: index == currentIndex }"
@click="onClickLi(index)"
>
{{ item.names }}
</li>
</ui>
</div>
</template>
css
<style lang="scss" scoped>
.a-page {
padding: 30px;
}
li {
color: #333;
}
.active {
color: red !important;
}
</style>
js
<script setup>
import {ref} from 'vue'
let obj = [
{ names: '唐僧', checked: false },
{ names: '孙悟空', checked: false },
{ names: '猪八戒', checked: false },
{ names: '悟静', checked: false },
{ names: '玫瑰', checked: false },
{ names: '向日葵', checked: false },
{ names: '百合', checked: false },
{ names: '海棠', checked: false }
]
const currentIndex = ref()
const onClickLi = (index) => {
currentIndex.value = index
}
</script>
多选业务:
template
<div class="a-page">
<ui>
<li
v-for="(item, index) in obj"
:key="index"
:class="{ active: item.checked }"
@click="onClickLi(item, index)"
>
{{ item.names }}
</li>
</ui>
</div>
js
<script setup>
import { ref } from 'vue'
let obj = ref([
{ names: '唐僧', checked: false, id: 1 },
{ names: '孙悟', checked: false, id: 2 },
{ names: '猪八', checked: false, id: 3 },
{ names: '悟静', checked: false, id: 4 },
{ names: '玫瑰', checked: false, id: 5 },
{ names: '向日', checked: false, id: 6 },
{ names: '百合', checked: false, id: 7 },
{ names: '海棠', checked: false, id: 8 }
])
const list = ref([]) //存储多选的数据
const onClickLi = (item, index) => {
obj.value.forEach((item1) => {
if (item.id == item1.id) {
item1.checked = !item1.checked
if(item1.checked){
list.value.push(item1)
}else{
list.value.splice(list.value.indexOf(item1),1)
}
}
})
console.log(list.value);
}
</script>
下面贴出来实验代码:
巧妙的利用数组的some和filter方法,进行数据的多选 / style控制 及 选择限制,项目中可以择优选择套用
<template>
<div>
<div v-for="tag in tags" :key="tag.id" :class="{ 'selected': isSelected(tag) }" @click="toggleTag(tag)">
{{ tag.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
tags: [
{ id: 1, name: '标签1' },
{ id: 2, name: '标签2' },
{ id: 3, name: '标签3' },
{ id: 4, name: '标签4' },
{ id: 5, name: '标签5' },
],
selectedTags: [],
};
},
computed: {
selectedCount() {
return this.selectedTags.length;
},
},
methods: {
toggleTag(tag) {
if (this.selectedCount >= 3 && !this.isSelected(tag)) {
return;
}
console.log(this.isSelected(tag));
if (this.isSelected(tag)) {
this.selectedTags = this.selectedTags.filter((t) => t.id !== tag.id);
} else {
this.selectedTags.push(tag);
}
console.log(this.selectedTags);
},
isSelected(tag) {
return this.selectedTags.some((t) => t.id === tag.id);
},
},
};
</script>
<style>
.selected {
background-color: #ccc;
}
</style>