简体   繁体   中英

V-bind class multiple options

I am trying to give one of two classes to an element depending on one of the three possible input variables. My vue.js code

<input type='text' class='inputwordtext' v-bind:class="[{(wordupload.firstchoice.selected == 'Zinnenlijst') : wordlongwidth}, {(wordupload.firstchoice.selected != 'Zinnenlijst') : wordshortwidth}]">

If wordupload.firstchoice.selected == Zinnenlijst it should get the class wordlongwidth, otherwise it should get the class wordshortwidth, how can this be done?

You could do this with a single inline expression using a tenary operator:

<input 
  type='text' 
  class='inputwordtext'
  :class="wordupload.firstchoice.selected === 'Zinnenlijst' ? 'wordlongwidth' : 'wordshortwidth'"
>

But, it would be more readable to make it a computed property:

computed: {
  inputClass() {
    let selected = this.wordupload.firstchoice.selected;
    return (selected === 'Zinnenlijst') ? 'wordlongwidth' : 'wordshortwidth';
  }
}

And then reference that computed property in your template:

<input type='text' class='inputwordtext' :class="inputClass">

The vue.js documentation suggests to use a ternary expression and to combine v-bind:class and your regular class like so:

<input type='text' :class="[wordupload.firstchoice.selected === 'Zinnenlijst' ? 'wordlongwidth' : 'wordshortwidth', 'inputwordtext']">

To see where they talk about this and learn more about class binds check out their documentation:

https://v2.vuejs.org/v2/guide/class-and-style.html#Array-Syntax

And you learn more about ternary expressions check out this source:

https://www.w3schools.com/js/js_comparisons.asp

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