Mon modèle de 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="/images/photo.picture" alt="">
</a>
</div>
Ma méthode check ():
check(index) {
if(!("checked" in this.photos[index]))
this.photos[index].checked = true
else
this.photos[index].checked = !this.photos[index].checked
},
Tout semble correct mais cela ne fonctionne pas. Quel pourrait être le problème?
Réponses:
3 pour la réponse № 1Vue ne peut pas détecter les modifications apportées à un index d'un tableau.
Obtenez une référence à la photo
objet de la index
transmis à check()
et ensuite utiliser Vue.set()
pour mettre à jour le tableau comme suit:
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);
},
3 pour la réponse № 2
Que diriez-vous juste @click.prevent="$set(photo, "checked", !photo.checked)"
et oublier le gestionnaire?
<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="/images/photo.picture" alt="">
</a>
</div>
Si vous souhaitez utiliser le gestionnaire:
<div class="col-sm-4 col-xs-6 thumb" v-for="(photo, index) in photos"
@click.prevent="check(photo)">
Et
check(photo) {
this.$set(photo, "checked", !photo.checked)
},