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

标签 javascript vue.js vuejs2

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/

相关文章:

javascript 排序 obj 改变 id #'s

javascript - 我在 Vue.js 中创建了一个不起作用的模式组件

javascript - 2 个组件几乎完全相同。唯一的区别是每个组件都有不同的 GET 请求。合并他们?

javascript - 如何在保留 option_selection.js 的同时在变体选择下拉列表中包含变体价格

javascript - gotoSlide(index) 在 sliderPro 中不起作用

javascript - Vue.js 和 The Movie Database API 返回错误 403

vue.js - 使用 Vee-Validate 在提交时验证子输入组件

vuejs2 - 如何将对象项添加到计算属性项以放置在路由参数中?

vuejs2 - 在 VueJS 中流畅地制作动画 v-show

javascript - 无法在页面刷新时获取元素宽度