单击Vue.js交换类

时间:2019-01-05 18:59:16

标签: javascript vue.js

我认为这很简单,但是我一直在努力理解如何将一个类应用于按钮,然后在单击后更改为另一个类。我有多个按钮可以用作过滤器,用户只能选择一个按钮,并且选择后只有该按钮会突出显示。我可以做到,但是我似乎无法删除初始类以使用v-bind更改文本颜色。初始类别不会处于活动状态,选择后,突出显示类别将更改文本颜色。

这是没有添加noactive类的jsfiddle,我只是不知道什么是最佳解决方案。

JSFiddle

new Vue({
  el: '#vue',
  data: {
    selected: ''
  }
})
.highlight {
  color: green;
  font-size: 16px;
  border: 0;
  background: 0;
}


.notactive {
 color: grey;
 border: 0;
 background: 0;
 font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue">
  <button @click="selected = 1" :class="{highlight:selected == 1}">Button1</button>
  <button @click="selected = 2" :class="{highlight:selected == 2}">Button2</button>
  <button @click="selected = 3" :class="{highlight:selected == 3}">Button3</button>
</div>

2 个答案:

答案 0 :(得分:1)

new Vue({
  el: '#vue',
  data: {
    selected: ''
  }
})
.highlight {
  color: green;
  font-size: 16px;
  border: 0;
  background: 0;
}

.notactive {
  color: grey;
  border: 0;
  background: 0;
  font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue">
  <button @click="selected = 1" :class="{highlight:selected == 1, notactive:selected !== 1}">Button1</button>
  <button @click="selected = 2" :class="{highlight:selected == 2, notactive:selected !== 2}">Button2</button>
  <button @click="selected = 3" :class="{highlight:selected == 3, notactive:selected !== 3}">Button3</button>
</div>

答案 1 :(得分:0)

如果我了解您的问题,我相信答案就很简单,只要在类绑定中为非活动类扩展另一个条目即可:

<div id="vue">
 <button @click="selected = 1" :class="{highlight:selected == 1, notactive:selected !== 1}">Button1</button>
 <button @click="selected = 2" :class="{highlight:selected == 2, notactive:selected !== 2}">Button2</button>
 <button @click="selected = 3" :class="{highlight:selected == 3, notactive:selected !== 3}">Button3</button>
</div>

这是更新的小提琴-https://jsfiddle.net/chrismarx/ptk247wz/