vue 绑定样式

前提:

有一个列表,使用 v-for 循环出来,点击哪一项,哪一项文字变色,这个功能很好实现,写好 active 类之后,在 html 中直接绑定即可,例如:

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: '#428bca';
}

但是现在问题是,这个色值是服务器传过来的值,所以只能用如下方法:

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: '#428bca',
    nowIndex: 0,
    list: [
      {id: 1, name: 'apple'},
      {id: 2, name: 'banana'},
      {id: 3, name: 'orange'}
    ]
  }
},
methods: {
  selectOne (index) {
    this.nowIndex = index
  }
}

不知道有没有更加简单的写法或者其他的写法可以实现呢?

阅读 1.9k
1 个回答
<span :style="index === nowIndex ? ('color:' + themeColor + ';') : ''">{{ item.name }}</span>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题