我有一个列表,里面有一些项目。单击一个项目后,我想向该项目添加 active
类,并关闭其他项目(如果有任何具有 active
类的项目)。我怎样才能实现它?这是 fiddle .
new Vue({
el: "#app",
data: {
lorem: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
items: [
{ text: "Learn JavaScript", isActive: false },
{ text: "Learn Vue", isActive: false },
{ text: "Play around in JSFiddle", isActive: false },
{ text: "Build something awesome", isActive: false }
]
},
methods: {
toggleItem(item) {
if(item.isActive) {
this.items.forEach((item1) => {
item1.isActive = false
})
} else
if(!item.isActive) item.isActive = !item.isActive
},
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
padding: 20px;
}
.item-active p {
color: green;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7701021237455942594641" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.js"></script>
<div id="app">
<div v-for="(item, index) in items" @click="toggleItem(item)" :class="{active: item.isActive}">
<h1 style="font-weight: bold">{{item.text}}</h1>
<div v-if="item.isActive" class="item-active">
<p>{{ lorem }}</p>
</div>
</div>
</div>
最佳答案
当您一次只有一件事情应该处于事件状态时,您可能希望有一个变量以某种方式指示哪个项目处于事件状态,而不必更新 Accordion 中的所有项目。
<template>
<div id="app">
<div v-for="(item, index) in items" @click="toggleItem(index)" :class="{active: isActive === index}">
<h1 style="font-weight: bold">{{item.text}}</h1>
<div v-if="isActive === index" class="item-active">
<p>{{ lorem }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: "App",
data () {
return {
lorem: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
items: [
{ text: "Learn JavaScript" },
{ text: "Learn Vue" },
{ text: "Play around in JSFiddle" },
{ text: "Build something awesome" }
],
isActive: null
}
},
methods: {
toggleItem(index) {
this.isActive = index;
},
}
};
</script>
<style>
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
padding: 20px;
}
.item-active p {
color: green;
}
</style>
我们不是查看项目来查看它是否处于事件状态,而是将数组中的索引与应该处于事件状态的项目进行比较。我们将该变量初始化为 null,这意味着默认情况下它们都没有打开。
关于javascript - 如何在 Vue 中仅使 Accordion 的一项处于事件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455337/