简体   繁体   中英

Vue.js - conditionally assign a CSS class

In a VueNative project, which is using NativeBase as a component library (thus the tags prefixed with nb- ), I have the following code. This is in the <template> tags and is part of the footer.vue file which contains navigation buttons. This logic is working fine to change the color of the tab (button) when the user presses it and it becomes active.

<nb-button :active="tab2" :onPress="toggleTab2" :style="{ backgroundColor: (activeTab == 'tab2') ? 'rgb(117, 110, 116)' : 'rgb(82, 74, 81)' }">
  <nb-text class="text">Instructions</nb-text>
</nb-button>

I'd like to replace :style with :class so all of the nb-button tags in the file refer to class names rather than hard coded background colors in each tag. Here is what I've tried -
in the <template> tags:

<nb-button :active="tab2" :onPress="toggleTab2" :class="{ (activeTab == 'tab2') ? "active" : "inactive" }">
  <nb-text class="text">Instructions</nb-text>
</nb-button>

in the <style> tags:

.inactive {
  background-color: rgb(82, 74, 81);
}
.active {
  background-color: rgb(117, 110, 116);
}

However, in the code editor a red squiggly line is showing under the :class line which says "'v-bind' directives require an attribute value". How can this be modified to work?

Edit Based on this post I have also tried the following:

<nb-button :active="tab2" :onPress="toggleTab2" :style="(activeTab == 'tab2') ? 'active' : 'inactive'">

But it acts like it ignores the class names. When the user chooses tab2, the default active color is displayed rather than the color specified in the active style.

你没有逃避""里面:class="{ (activeTab == 'tab2') ? "active" : "inactive" }"所以应该用'替换"并根据这个改变语法:

:class="{ active: (activeTab == 'tab2'), inactive: (activeTab !== 'tab2')}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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