連想配列のvalue更新をリアクティブにする方法【Vue.js】
次のように連想配列が定義されているとします。
data () { return { showEdit: {}, } },
上記に対して、次のような処理を行っても変更結果がリアクティブになりません。
this.showEdit[id] = false;
次のように記述する必要があります。
this.showEdit = Object.assign({}, this.showEdit, { [id]: !this.showEdit[id]});
連想配列は、v-forで生成した要素に対して表示などのコントロールをするのに使用でき、便利です。
<div v-for="(item, index) in itemList" :key="item.id" class="item"> <img :src="itemList[index].src" alt="image" class="item-image" @click="ctlShowEdit(item.id)"> <!-- 連想配列showEditを用いて、item.id毎に表示・非表示を切り替えることができる --> <div class="edit-button" v-show="showEdit[item.id]"> <button @click="changeImg(index, item.id)">CHANGE</button> <button @click="deleteImg(index, item.id)">DELETE</button> </div> </div>