我目前正在使用来自服务的数据制作手风琴(我已经制作了一个名为&#34的对象;群组和#34;例如清酒)。目前,我可以单击组名称,它将正确隐藏/显示描述,但它会打开所有实例。如何让它打开被点击的组,而不是全部?这是我的小提琴:https://jsfiddle.net/ch609uov/1/我知道我可以在我的群组var中使用open属性,但是我正在使用的actaul数据没有那个道具。因此,我需要使用它添加到我的Vue实例中的isExpanded prop。
var groups = {
"GROUP A": {
"name": "GROUP A",
"open": false,
"desc": "description 1",
"heading": "test",
"items": [
"item 1"
]
},
new Vue({
el: ".vue",
data: {
groups: groups,
heading: "Plan Communications",
isExpanded: false
}
})
如果您有任何疑问,请与我们联系!我是Vue的新手,所以我可能不会完美地解释它。谢谢!
答案 0 :(得分:2)
有几种方法可以实现这一点,第一种方式实际修改从外部资源返回的数据,使每个条目都有自己的open
属性:
let serviceDataExample = [{title: "some title 1"}, {title: "some title 2"}, {title: "some title 3"}];
serviceDataExample.forEach(obj => {
obj.open = false;
});
console.log(serviceDataExample);
// assign to your data object with `this` and use the open
// attribute individually in the template

在上文中,serviceDataExample
只是模拟表示数据的样子。
上述解决方案的缺点是,每次从资源中获取新数据时,在将其分配给数据对象之前,您必须重新运行forEach
。
这样做可以确保您不必使用显示设置来混淆原始(本地)资源数据:
var groups = {
"GROUP A": {
"name": "GROUP A",
"open": false,
"desc": "description 1",
"heading": "test",
"items": [
"item 1"
]
},
"GROUP B": {
"name": "GROUP B",
"open": false,
"desc": "description 2",
"items": [
"item 1",
"item 2",
"item 3",
"item 4",
"item 5",
"item 6",
"item 7"
]
},
"GROUP C": {
"name": "GROUP C",
"open": false,
"desc": "description 3",
"items": [
"item 1",
"item 2",
"item 3",
"item 4",
"item 5"
]
},
"GROUP D": {
"name": "GROUP D",
"open": false,
"desc": "description 4",
"items": [
"item 1",
"item 2",
"item 3",
"item 4",
"item 5",
"item 6",
"item 7"
]
},
"GROUP E": {
"name": "GROUP E",
"open": false,
"desc": "description 5",
"items": [
"item 1",
"item 2",
"item 3",
"item 4",
"item 5"
]
}
}
new Vue({
el: ".vue",
data: {
groups: groups,
heading: "Plan Communications",
// isExpanded: false,
expandedGroup: []
},
methods: {
isExpanded(key) {
return this.expandedGroup.indexOf(key) !== -1;
},
toggleExpansion(key) {
if (this.isExpanded(key))
this.expandedGroup.splice(this.expandedGroup.indexOf(key), 1);
else
this.expandedGroup.push(key);
}
}
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div class="container vue">
<div v-for="(group, key) in groups">
<a @click="toggleExpansion(key)" >{{group.name}}</a>
<ul v-show="isExpanded(key)">
<li>{{group.desc}}</li>
</ul>
<hr>
</div>
</div>
&#13;
在这里,我们正在创建一个外部数据属性,以便跟踪展开的组的索引。如果group
索引存在于本地expandedGroup
中,则它会打开,否则会关闭。
希望这有帮助!