Vue, why is there no if added here?

this sentence : the activeName of class= "{active: activeName = = gameName}" is a variable defined in data. The question I want to ask is why not add if judgment but compare the two variables directly activeName = = gameName ? What kind of usage is this? The novice asks everyone to explain

<div id="app">
  <ul><div>:</div>
      <li class="collection-item"
         v-for="gameName in gameNames"
         :class="{active: activeName == gameName}"
         @click="selected(gameName)">{{gameName}}
        </li> 
</ul>
</div>
new Vue({
  el: "-sharpapp",
  data: {
    gameNames: ["", "", "", "", "",""],
    activeName: ""
  },
  methods: {
    selected: function(gameName) {
      this.activeName = gameName
    }
  }
})
Jun.02,2021

: class= "{active: activeName = = gameName}"
means that if the result of activeName = = gameName is true, then add a class named active to li.
what do you mean by adding if judgment?

update
take a look at the source code

  if (val.__ob__) {
    var depId = val.__ob__.dep.id;
    if (seen.has(depId)) {
      return
    }
    seen.add(depId);
  }

roughly means to add the class name in: class to the native class.


according to your way of thinking, it can be written as : class= "activeName = = gameName? 'active':'"
is also feasible, depending on personal habits. Not with if, because the bound data can be expressions and variables, but not statements.


first of all, it is best not to nest div; in ul
. Secondly, I read the answer upstairs, and I also learned about it. After vue implements data binding, the bound data can be variables or expressions, so you can use the ternary operator in: class to directly determine whether the value of activeName is equal to gameName;
. When you say if, do you mean v-if?

about: class {active:flag} syntax
bind HTML Class

object syntax

We can pass an object to v-bind:class to dynamically switch class:

< div vtalk bindlass = "{active: isActive}" > < / div >

The syntax above indicates that the existence of the class active will depend on the truthiness of the data attribute isActive.

you can dynamically switch multiple class by passing in more properties in the object. In addition, the v-bind:class instruction can also coexist with the normal class attribute.

Menu