BootstrapVue 按钮状态:单击其他按钮时重置按钮

时间:2021-04-02 15:37:28

标签: vuejs2 toggle show-hide bootstrap-vue

考虑下面的代码

<div id='app'>
  <div class="card shadow bg-light m-4">
    <b-table striped hover :items="items" :fields="fields" responsive>
      <template #cell(age)="data">
        <b-button :pressed.sync="data.item.age_visible" pill variant="outline-danger">
          <span v-if="data.item.age_visible">{{data.item.age}}</span>
          <span v-else>Show Age</span>
        </b-button>
      </template>
    </b-table>
  </div>
</div>
new Vue({
  el: "#app",
  data() {
    return {
      fields: ['first_name', 'last_name', 'age'],
      items: [
        { age: 40, age_visible: false, first_name: 'Dickerson', last_name: 'Macdonald' },
        { age: 21, age_visible: false, first_name: 'Larsen', last_name: 'Shaw' },
        { age: 89, age_visible: false, first_name: 'Geneva', last_name: 'Wilson' },
        { age: 38, age_visible: false, first_name: 'Jami', last_name: 'Carney' }
      ]
    }
  },
});

给你

enter image description here

当您点击“显示年龄”时,年龄就会显示出来。在 codepen 上试试。

我的问题:

当有人点击“显示年龄”的不同行时,显示行中的年龄现在应该再次隐藏。我怎样才能做到这一点?

另外让我知道列 age_visible 是否真的有必要。

版本

  • Vue 2.6.12
  • 引导程序 4.6.0
  • BootstrapVue 2.21.2

1 个答案:

答案 0 :(得分:1)

我认为 age_visible 没有必要。这里的问题似乎是,一旦您移动到下一个按钮,您就永远不会对之前单击过的按钮执行任何操作。当您点击一个新按钮时,最后一个按钮应该会恢复到原来的状态。

我的想法是在 data() 中使用一些东西来跟踪当前索引,然后当您单击按钮时,它会检查当前索引是否与刚刚单击的按钮匹配。如果为真,则显示年龄,如果为假,则隐藏它。我的解决方案唯一奇怪的 CSS 问题是,除非您将鼠标悬停在按钮上,否则一旦点击按钮,它就不再保持红色。

这是我所拥有的

new Vue({
  el: "#app",
  data() {
    return {
      currentIndex: -1,
      fields: ['first_name', 'last_name', 'age'],
      items: [
        { index: 0, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
        { index: 1, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
        { index: 2, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
        { index: 3, age: 38, first_name: 'Jami', last_name: 'Carney' }
      ]
    }
  },
  methods: {
    setIndex(pendingIndex) {
      this.currentIndex = pendingIndex
    }
  }
});
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>

<div id='app'>
  <div class="card shadow bg-light m-4">
    <b-table striped hover :items="items" :fields="fields" responsive>
      <template #cell(age)="data">
        <b-button @click="setIndex(data.item.index)" pill variant="outline-danger">
          <span v-if="currentIndex === data.item.index">{{data.item.age}}</span>
          <span v-else>Show Age</span>
        </b-button>
      </template>
    </b-table>
  </div>
</div>