【问题标题】:Add class on click in vuejs在 vuejs 中单击添加类
【发布时间】:2018-01-02 03:02:06
【问题描述】:

我的 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.js vuejs2 vue-component vue-router


    【解决方案1】:

    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.

    【讨论】:

      【解决方案2】:

      只需@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)
      },
      

      【讨论】:

      • 这也是我的第一个想法。我不知道为什么,但是如果 photo 最初没有 checked 属性(在示例中似乎就是这种情况),这将不起作用。 jsfiddle.net/jb5fhscw/1
      • @thanksd 如果最初没有该属性,则需要通过 $set 进行设置。
      • 嗯,有道理
      • 我们应该打开一个问题
      • @ChadidiAbdellah 不,这是预期的行为。
      猜你喜欢
      • 2017-10-27
      • 2019-01-29
      • 2019-12-23
      • 2020-08-13
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      相关资源
      最近更新 更多