admin管理员组

文章数量:1399903

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?

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?

Share Improve this question asked Oct 9, 2017 at 17:17 JFugger_jrJFugger_jr 3131 gold badge4 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 puted property:

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

And then reference that puted property in your template:

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

The vue.js documentation suggests to use a ternary expression and to bine 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/v2/guide/class-and-style.html#Array-Syntax

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

https://www.w3schools./js/js_parisons.asp

本文标签: javascriptVbind class multiple optionsStack Overflow