gpt4 book ai didi

javascript - Vuejs 简单的动态 v-show 使用 index 和 falsey v-if 来切换元素

转载 作者:行者123 更新时间:2023-11-30 20:17:39 25 4
gpt4 key购买 nike

v-show 根据 index 切换元素的最佳解决方案是什么,我设法完成了切换部分,但是当您单击当前打开的元素时不会关闭。

<div v-for="(btn, index) in dataArray">
<button @click="toggle(index)">{{ btn.name }}</button>
<p v-show="isOpenIndex === index"> {{ btn.desc }} </p>
</div>

如果我添加了假条件,当您单击另一个按钮但它不会打开您单击的元素时它会关闭打开的条件

<div v-for="(btn, index) in dataArray">
<button @click="toggle(index)">{{ btn.name }}</button>
<p v-show="isOpenIndex === index" v-if="isOpen"> {{ btn.desc }} </p>
</div>

jsFiddle Example

最佳答案

编辑 1:正如@MrNew 所说,toggle 方法中的三元运算符就足够了:

...
methods: {
toggle: function(index){
this.isOpenIndex = ( this.isOpenIndex == index ) ? null : index;
}
}

原答案:

将这两个条件添加到您的 toggle 方法:如果定义了 isOpenIndex,检查它是否与当前元素的 index 匹配以将其关闭(将其返回到 null),如果不是,则将其设置为 index。如果未定义,则将其设置为 index:

methods: {
toggle: function(index){
if( this.isOpenIndex !== null ){
this.isOpenIndex = ( this.isOpenIndex == index ) ? null : index;
} else {
this.isOpenIndex = index;
}
}
}

关于javascript - Vuejs 简单的动态 v-show 使用 index 和 falsey v-if 来切换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51775929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com