2017-07-26 12 views
0

マイVUEテンプレートクラスを追加します。vuejsでクリックで

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

すべてが正しいようだが、それは働いていない:

<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> 

マイチェック()メソッドを。何が問題なの?

答えて

3

Vue cannot detect changes to an index of an array.

check()に渡さindexphotoオブジェクトへの参照を取得して、そのような配列を更新するためにVue.set()を使用します。ちょうど@click.prevent="$set(photo, 'checked', !photo.checked)"について

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.

3

方法とハンドラを忘れる?

<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) 
}, 
+0

あまりにも私が最初に考えました。理由は分かりませんが、 '写真'が最初に 'checked'プロパティを持っていなければ、これはうまくいきません(この例ではそうです)。 https://jsfiddle.net/jb5fhscw/1/ – thanksd

+0

@thanksd最初にプロパティがない場合は、$ setで設定する必要があります。 – Bert

+0

ああ意味があります – thanksd

関連する問題