1、更新数组中元素值:vue.set(this.对象,下标,新值)
- 由于 JavaScript 的限制,利用索引直接修改数组元素时,Vue 不能检测数组的变动:
- 正确的方法:
- Vue.set(vm.items, indexOfItem, newValue)
- vm.items.splice(indexOfItem, 1, newValue)
- vm.$set(vm.items, indexOfItem, newValue)
- vm即this
<div id="app">
<span>{
{curstatus}}</span>
<div v-for="(book, index) in books" v-bind:key='book'>
<span>{
{ book }}</span>
<input type="text" v-bind:placeholder="book" >
</div>
<button @click='EditBooks'>更换图书(将python改成Python)</button>
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
curstatus:"变更前",
books:["java","python","C#"]
},
methods:{
EditBooks(){
//不能更新视图
this.books[1]="Python"
//这样才行
Vue.set(this.books,1,"Python")
//或 this.books.splice(1,1,"Python")
//或 this.$set(this.books,1,"Python")
this.curstatus="变更后"
},
},
});
</script>
2、更新数组的长度:vue.set(this.对象,下标,新值)
- 由于 JavaScript 的限制,直接修改数组长度,Vue 不能检测数组的变动:
- 正确的方法: vm.items.splice(newLength)
<div id="app">
<span>已绑定</span>>
<div v-for="(book, index) in books" v-bind:key='book'>
<span>{
{ book }}</span>
<input type="text" v-bind:placeholder="book" >
</div>
<button @click='EditBooks'>更换图书(将数组长度变成2)</button>
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
books:["java","python","C#"]
},
methods:{
EditBooks(){
//不能更新视图
this.books.length=2
//这样才行
this.books.splice(2)
},
},
});
</script>