Vue文檔關於這一點解釋的很明白,筆者再也不贅述,各位必定要看完文檔再來
以下例中,是要實現
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>
以下例中,是要實現給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>
文檔:Vue.set( target, propertyName/index, value )
注意Vue.set()還有個別名,用於vue實例——vue.$set( target, propertyName/index, value )
vue
數組
以下例中,是要實現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>