vue uni-app 的set用法總結

<template>
    <div id="app2">
        <p v-for="item in items" :key="item.id">{{item.message}}</p>
        <button class="btn" @click="handClick()">更改數據</button>    
    </div>
</template>

<script>
export default {
    data() {
        return {
            items: [
                { message: "one", id: "1" },
                { message: "two", id: "2" },
                { message: "three", id: "3" }
            ]
        };
    },
    mounted(){
        this.items[0]={message:"測試",id:"4"};  //此時對象的值更改了,但是視圖沒有更新
        this.$set(this.items,0,{message:"測試",id:"4"}); //$set可以觸發更新視圖
        console.log(this.items)
    },
    methods: {
        // 調用方法:Vue.set( target, key, value )

        // target:要更改的數據源(可以是對象或者數組)

        // key:要更改的具體數據

        // value :重新賦的值
        handClick() {
            //Vue methods中的this 指向的是Vue的實例,這裏可以直接在this中找到items
            this.$set(this.items, 0, { message: "更改one的值", id: "0" });
        },
    }
};
</script>

<style>
</style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章