javascript - v-show 在 v-for 循环中,我只需要打开单击的选项
问题描述
我刚开始学习 Vue.js,我需要一些帮助。我在 v-for 循环中设置了一个 v-show,循环中有一个显示按钮,当我点击它时,它会打开所有隐藏的 div,我希望它只打开被点击的相关的. 也许有另一种方法可以做到这一点,或者我一直在阅读的更好的方法 v-show 可能不适合在循环中使用。
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: "Montserrat", sans-serif;
}
.content {
width: 100px;
height: 100px;
background-color: red;
}
.contenttwo {
width: 50px;
height: 50px;
background-color: green;
}
</style>
</head>
<body>
<div id="root">
<div v-for="item in dropdownVoices" :key="item.voice" class="">
<div v-show="active" class="content">
</div>
<div v-show="!active" class="contenttwo">
</div>
<button type="button" name="button" v-on:click="active = !active">Change me</button>
</div>
</div>
<script charset="utf-8">
var app = new Vue({
el: '#root',
data: {
active:true,
dropdownVoices:[
{ voice: 'One' },
{ voice: 'Two' },
{ voice: 'Three' },
{ voice: 'Four' },
{ voice: 'Five' },
{ voice: 'Six' }
],
},
method:{
}
});
Vue.config.devtools = true;
</script>
</body>
</html>
在此先感谢您的帮助。
解决方案
问题是您仅使用一个变量来跟踪活动更改,active
但您需要跟踪每个项目,因此您有两个选项可以为每个项目对象添加一个活动属性或跟踪数组中的活动项目。我要给你看第一个
// script
data: {
dropdownVoices:[
{ voice: 'One' , active: true},
{ voice: 'Two' , active: true},
{ voice: 'Three' , active: true},
{ voice: 'Four' , active: true},
{ voice: 'Five' , active: true},
{ voice: 'Six', active: true }
],
}
// template
<div v-for="item in dropdownVoices" :key="item.voice" class="">
<div v-show="item.active" class="content"></div>
<div v-show="!item.active" class="contenttwo"></div>
<button type="button" name="button" v-on:click="item.active = !item.active">Change me</button>
</div>
注意:如果您只想更改 div 样式,可以使用绑定类来完成。
<div :class="item.active ? 'content' : 'contenttwo'"></div>
推荐阅读
- tensorflow - 如何在 TF 2.0 数据集映射步骤中从张量中获取和使用值?
- java - 在集成测试中模拟嵌入对象
- ubuntu - Raspberrypi中的对等方重置连接?
- codeigniter-2 - 运行 migrate codeigniter2 时获取 500 他的页面不工作
- c# - SSIS C#脚本任务不读取变量或参数
- angular - 从我的 Angular 火力库中获取用户个人资料
- google-chrome - 仅过滤有错误的请求 - Google chrome network
- android - 如何从一个对话框过渡到另一个对话框
- c++ - 是否在向量 C++ 中读取和写入向量线程安全操作?
- javascript - Javascript级联下拉加载问题