詳解Vue的set方法

1、起源:若直接對data內的數組、對象進行修改,不會觸發視圖更新

Vue文檔關於這一點解釋的很明白,筆者再也不贅述,各位必定要看完文檔再來

數組更新監測
對象更新監測html

2、如何正確修改數組、對象以觸發視圖更新

2.1 數組

2.1.1 使用vue提供的變異方法

image.png

2.1.2 直接將data中的數組整個替換

以下例中,是要實現 vm.items[1] = 'excess'
<body>
<div id="app">
    <ul>
        <li v-for="(item, index) in items">
            {{ index }} : {{ item }}
        </li>
    </ul>
</div>

<script>
let vm = new Vue({
    el: '#app',
    data: {
        items: ['a', 'b', 'c']
    },
    created() {
        this.items = ['a', 'test', 'c']
    }
})
</script>
</body>

2.1.3 使用set方法【後文詳解】

2.2 對象

2.2.1 直接將data中的Object整個替換

以下例中,是要實現給object新增一個鍵值對 {test: 'newthing'}
<body>
<div id="app">
    <ul>
        <li v-for="(value, name) in object">
            {{ name }} : {{ value }}
        </li>
    </ul>
</div>

<script>
let vm = new Vue({
    el: '#app',
    data: {
        object: {
            title: 'How to do lists in Vue',
            author: 'Jane Doe',
            publishedAt: '2016-04-10'
        }
    },
    created() {
        this.object = {
            title: 'How to do lists in Vue',
            author: 'Jane Doe',
            publishedAt: '2016-04-10',
            test: 'newthing'
        }
    }
})
</script>
</body>

2.2.2 使用set方法【後文詳解】

3、使用set方法

3.1 官方API文檔

文檔:Vue.set( target, propertyName/index, value )
注意Vue.set()還有個別名,用於vue實例——vue.$set( target, propertyName/index, value )vue

3.2 應用

數組
以下例中,是要實現 vm.items[1] = 'excess'
<body>
<div id="app">
    <ul>
        <li v-for="(item, index) in items">
            {{ index }} : {{ item }}
        </li>
    </ul>
</div>

<script>
let vm = new Vue({
    el: '#app',
    data: {
        items: ['a', 'b', 'c']
    },
    created() {
        this.$set(this.items, 1, 'excess')
    }
})
</script>
</body>
對象
以下例中,是要實現給object新增一個鍵值對 {test: 'newthing'}
<body>
<div id="app">
    <ul>
        <li v-for="(value, name) in object">
            {{ name }} : {{ value }}
        </li>
    </ul>
</div>

<script>
let vm = new Vue({
    el: '#app',
    data: {
        object: {
            title: 'How to do lists in Vue',
            author: 'Jane Doe',
            publishedAt: '2016-04-10'
        }
    },
    created() {
        this.$set(this.object, 'test', 'newthing')
    }
})
</script>
</body>
相關文章
相關標籤/搜索