在 vuejs 中点击添加 class

Add class on click in vuejs

我的 vue 模板:

<div 
  class="col-sm-4 col-xs-6 thumb" 
  v-for="(photo, index) in photos" 
  @click.prevent="check(index)"
>
  <a class="thumbnail" :class="{'active': photo.checked}">
    <img class="img-responsive" :src="photo.picture" alt="">
  </a>
</div>

我的 check() 方法:

check(index) {
  if(!("checked" in this.photos[index]))
    this.photos[index].checked = true
  else
    this.photos[index].checked = !this.photos[index].checked
},

一切似乎都正确,但它不工作。可能是什么问题?

Vue cannot detect changes to an index of an array.

获取传递给 check()indexphoto 对象的引用,然后使用 Vue.set() 像这样更新数组:

check(index) {
  let photo = this.photos[index];

  if (!("checked" in photo)) {
    photo.checked = true
  } else {
    photo.checked = !photo.checked
  }

  Vue.set(this.photos, index, photo);
},

Here's a fiddle.

@click.prevent="$set(photo, 'checked', !photo.checked)" 而忘记处理程序怎么样?

<div class="col-sm-4 col-xs-6 thumb" v-for="(photo, index) in photos" 
    @click.prevent="$set(photo, 'checked', !photo.checked)">
  <a class="thumbnail" :class="{'active': photo.checked}">
    <img class="img-responsive" :src="photo.picture" alt="">
  </a>
</div>

如果你想使用处理程序:

<div class="col-sm-4 col-xs-6 thumb" v-for="(photo, index) in photos" 
     @click.prevent="check(photo)">

check(photo) {
  this.$set(photo, 'checked', !photo.checked)
},