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>