天天看點

Vue重新渲染資料

Vue

 不能檢測以下數組的變動:

1、當你利用索引直接設定一個數組項時

2、當你修改數組的長度時

3、對象屬性的添加或删除

來源: 

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

代碼引入vue

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></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 強制元件重新渲染(重置)

繼續閱讀