简体   繁体   English

在Vue中,单击时将多个按钮之一更改为活动状态

[英]In Vue change one of multiple buttons to active when clicked

I have three buttons, and when I click one of them, it needs to become active, and other two must become inactive. 我有三个按钮,当我单击其中一个按钮时,它需要变为活动状态,而另两个按钮必须变为非活动状态。 In code below all three are changing together to active/inactive on click event. 在下面的代码中,所有三个事件都一起变为有效/无效的点击事件。 Is there an elegant way to solve this, instead of creating three values isActive1, isActive2, isActive3 for all three buttons? 有没有一种优雅的方法可以解决此问题,而不是为所有三个按钮创建三个值isActive1, isActive2, isActive3

<div class="btn-group" role="group">
    <button type="button" :class="getActiveClass()" v-on:click="getWeather('Misto Kyyiv'); isActiveBtn = !isActiveBtn">Kyiv</button>
    <button type="button" :class="getActiveClass()" v-on:click="getWeather('London'); isActiveBtn = !isActiveBtn">London</button>
    <button type="button" :class="getActiveClass()" v-on:click="getWeather('New York'); isActiveBtn = !isActiveBtn">New York</button>
</div>
data: function() {
    return {      
        isActiveBtn: false
    }
}, 
getActiveClass() {
    if (this.isActiveBtn) {
        return "btn btn-secondary active";
    } else {
        return "btn btn-secondary";
    }
}

Having three data properties would be one way to do it. 具有三个数据属性将是执行此操作的一种方法。 Or you might have a prop activeBtn where you store the name (or index) of the active btn. 或者,您可能有一个属性activeBtn,用于存储活动btn的名称(或索引)。 You will then need to change the getActiveClass method to accept an argument with the name or index of the button. 然后,您需要更改getActiveClass方法以接受带有按钮名称或索引的参数。

I would suggest to store the currently active city as your data. 我建议将当前活动的城市存储为您的数据。 In getActiveClass pass and compare the ID of a button to the currently active ID and set the class accordingly. getActiveClass ,将按钮的ID与当前活动的ID进行比较,然后相应地设置类。

<div class="btn-group" role="group">
  <button type="button" :class="getActiveClass('Kyiv')" v-on:click="getWeather('Misto Kyyiv'); activeId = 'Kyiv'">Kyiv</button>
  <button type="button" :class="getActiveClass('London')" v-on:click="getWeather('London'); activeId = 'London'">London</button>
  <button type="button" :class="getActiveClass('New York')" v-on:click="getWeather('New York'); activeId = 'New York'">New York</button>
</div>
getActiveClass(id) {
  if (id === this.activeId) {
    return "btn btn-secondary active";
  } else {
    return "btn btn-secondary";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM