代码引入vue
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
通过索引赋值,修改数组后没有检测到变化
<div id="app"> <template v-for="(color, index) in colors"> <div @click="changeItem(index)">{{color}}</div> </template> </div> <script> var app = new Vue({ el: "#app", data(){ return { colors: ["red", "black", "green", "yellow", "blue"] } }, methods:{ changeItem(index){ this.colors[index] = "white"; console.log(this.colors[index]); } } }) </script>
方案一
通过v-if="isShow" 更新
<div id="app"> <template v-for="(color, index) in colors" v-if="isShow"> <div @click="changeItem(index)">{{color}}</div> </template> </div> <script> var app = new Vue({ el: "#app", data(){ return { isShow: true, colors: ["red", "black", "green", "yellow", "blue"] } }, methods:{ changeItem(index){ this.colors[index] = "white"; console.log(this.colors[index]); // 重新渲染数据 this.isShow= false // 更新dom this.$nextTick(()=>{ this.isShow = true }) } } }) </script>
方案二
key 值变更时,会自动的重新渲染
<div id="app"> <div v-for="(color, index) in colors" :key="colorsKey"> <div @click="changeItem(index)" >{{color}}</div> </div> </div> <script> var app = new Vue({ el: "#app", data(){ return { colorsKey: 0, colors: ["red", "black", "green", "yellow", "blue"] } }, methods:{ changeItem(index){ this.colors[index] = "white"; console.log(this.colors[index]); // 触发渲染 this.colorsKey++; } } }) </script>