Vue 不能检测以下数组的变动:
1、当你利用索引直接设置一个数组项时
2、当你修改数组的长度时
3、对象属性的添加或删除

来源: https://cn.vuejs.org/v2/guide/list.html

代码引入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>    

参考
vue 强制组件重新渲染(重置)

Logo

前往低代码交流专区

更多推荐