如何在Vue中将样式化的类应用于按钮,但一次只能激活一个按钮?

时间:2018-10-14 12:27:14

标签: javascript vue.js

我设法使此按钮类从初始更改为活动,但是我想拥有多个按钮,但活动类仅应在任何时候应用于一个按钮。

<button :class="{'initial': activeTab !== 1, 'is-active': activeTab === 1}" name="button" @click="setActiveTab">BUTTON 1</button>

  activeTab: 0

  methods: {
      setActiveTab(){
        this.activeTab = 1;
      }
  }

  .is-active {
  color: blue
}

.initial {
color: red;
}

但希望拥有:

<button :class="{'initial': activeTab !== 1, 'is-active': activeTab === 1}" name="button" @click="setActiveTab">BUTTON 1</button>
<button :class="{'initial': activeTab !== 1, 'is-active': activeTab === 1}" name="button" @click="setActiveTab">BUTTON 2</button>
<button :class="{'initial': activeTab !== 1, 'is-active': activeTab === 1}" name="button" @click="setActiveTab">BUTTON 3</button>

任何帮助都会得到很大的帮助。

1 个答案:

答案 0 :(得分:2)

您只需将ID传递给您的setActiveTab方法

new Vue({
  el: "#app",
  data: {
activeTab: 0
  },
  methods: {
      setActiveTab(id){
        this.activeTab = id;
      }
  }
})
<div id="app">
  <button :class="{'initial': activeTab !== 1, 'is-active': activeTab === 1}" name="button" @click="setActiveTab(1)">BUTTON 1</button>
  <button :class="{'initial': activeTab !== 2, 'is-active': activeTab === 2}" name="button" @click="setActiveTab(2)">BUTTON 2</button>
  <button :class="{'initial': activeTab !== 3, 'is-active': activeTab === 3}" name="button" @click="setActiveTab(3)">BUTTON 3</button>
</div>

See this JSFiddle

您可以使用v-for来整理一些东西。

<div id="app">
  <button v-for="id in 3" :class="{'initial': activeTab !== id, 'is-active': activeTab === id}" name="button" @click="setActiveTab(id)">BUTTON {{ id }}</button>
</div>

JSFiddle