1.控制显隐:单独用一个变量记录状态,不去改变原数组
手风琴效果:
<template>
<div class="home">
<ul>
<li v-for="(item, index) in list" :key="index" @click="changeOne(item)">
<div>
<span>{{ expandList.indexOf(item.id) > -1 ? "-" : "+" }}</span>
<span>{{ item.title }}</span>
</div>
<div class="content" v-if="expandList.indexOf(item.id) > -1">
{{ item.content }}
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "Home",
components: {},
data() {
return {
expandList: [],
list: [
{ id: 1, content: "这是内容1", title: "这是标题1" },
{ id: 2, content: "这是内容2", title: "这是标题2" },
{ id: 3, content: "这是内容3", title: "这是标题3" },
{ id: 4, content: "这是内容4", title: "这是标题4" },
],
};
},
methods: {
change(item) {
// 点击就展开 收起
const index = this.expandList.findIndex((e) => e === item.id);
// expandList数组中包含就删除 不包含就删除 根据数组中是否有值来控制展开收起
index > -1
? this.expandList.splice(index, 1)
: this.expandList.push(item.id);
},
changeOne(item) {
// 每次只能点击一个展开
const index = this.expandList.findIndex((e) => e === item.id);
this.expandList = []; // 每次切换先将数组清空,点击的不是自身则添加 --每次最多展开一个
if (index === -1) {
this.expandList.push(item.id);
}
},
},
};
</script>
<style scoped lang="less">
li {
span {
cursor: pointer;
}
.content {
margin-left: 20px;
}
}
</style>
2,用include代替一个一个的判断
hasAnimals(type) {
const animals = ["cat", "pig", "dog"];
// return type === "cat" || type === "pig" || type === "dog";
return animals.includes(type);
},
3,用键值对obj[key]代替switch
findType(type) {
const mime = {
".323": "text/h323",
".3gp": "video/3gpp",
".aab": "application/x-authoware-bin",
".aam": "application/x-authoware-map",
".aas": "application/x-authoware-seg",
};
return mime[type];
// switch (type) {
// case ".323":
// return "text/h323";
// break;
// case ".3gp":
// return "video/3gpp";
// break;
// case ".aab":
// return "application/x-authoware-bin";
// break;
// }
},