Vue binding style

< H2 > premise: < / H2 >

there is a list. Use v-for to loop out, click on which item and which text changes color. This function is easy to implement. After writing the active class, you can bind it directly in html, for example:

html:

<ul>
  <li v-for="(item, index) in list"
    :class="{"active": index === nowIndex}"
    @click="selectOne(index)">
    {{ item.name }}
  </li>
</ul>

js:

selectOne (index) {
  this.nowIndex = index
}

css:

.active {
  color: "-sharp428bca";
}

but the problem now is that this color value is a value passed from the server, so we can only use the following methods:

html:

<div>
  <ul>
    <li v-for="(item, index) in list" :key="item.id" @click="selectOne(index)">
      <span v-if="index === nowIndex" :style="{color: themeColor}">{{ item.name }}</span>
      <span v-else>{{ item.name }}</span>
    </li>
  </ul>
</div>

js:

data () {
  return {
    themeColor: "-sharp428bca",
    nowIndex: 0,
    list: [
      {id: 1, name: "apple"},
      {id: 2, name: "banana"},
      {id: 3, name: "orange"}
    ]
  }
},
methods: {
  selectOne (index) {
    this.nowIndex = index
  }
}

I wonder if there is a simpler way to write it or other ways to write it.

Mar.09,2021

<span :style="index === nowIndex ? ('color:' + themeColor + ';') : ''">{{ item.name }}</span>
Menu