Search code examples
javascriptcssvue.jsvuejs2vue-native

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.


Solution

  • You're not escaping the "" inside :class="{ (activeTab == 'tab2') ? "active" : "inactive" }" so should replace " by ' and change the syntax based on this:

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