Vue.js在项目列表中单击的项目上突出显示颜色吗?

时间:2018-06-26 05:38:23

标签: javascript vue.js

当单击特定项目时,如何在项目列表中突出显示该项目?我们应该使用id作为参考吗?

<li v-for="todo in todos">
  <label>
    <a href="#"
      v-on:click="toggle(todo)"
      :style="{color:activeColor}"
      >


      {{ todo.text }}

    </a>

  </label>
</li>
toggle: function(todo){

  this.activeColor = 'red'
}

我在这里尝试过: https://jsfiddle.net/eywraw8t/110976/

1 个答案:

答案 0 :(得分:2)

您可以添加activeIndex来存储当前活动索引:

<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="(todo, idx) in todos">
      <label>
        <a href="#"
          v-on:click="toggle(idx)"
          v-bind:checked="todo.done"
          :class="{'active': idx == activeIndex}"
          >
          {{ todo.text }}

        </a>

      </label>
    </li>
  </ol>
</div>

new Vue({
  el: "#app",
  data: {
    activeColor:String,
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: false },
      { text: "Build something awesome", done: false }
    ],
    activeIndex: null
  },
  methods: {
    toggle: function(index){
        this.activeIndex = index
    }
  }

和css

.active {
  color: red;
}

演示:https://jsfiddle.net/Lv7eanru/