数组:
当数组元素的改变数组长度改变不能触发状态更新
arr[n]='x'; 但如果元素是一个对象(非数组),修改是响应式的
arr.length=n;
解决方法:
第一种:Vue.set(数组对象,索引,值); 或this.$set(...)
第二种:调用splice方法
对象:
(1)当添加和删除属性时,新的属性和删除的属性不是响应式的
解决方法:
Vue.set(对象名,'属性',属性的值); 设置一次后,该属性就会被vue数据绑定
(2)为已有对象赋值多个新属性
Object.assign(this.someObject, { a: 1, b: 2 }) 此种方式不会将新属性变成响应式,因为并没有调用someObject对象的set和get方法
解决方法:
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
重新赋值给someObject,会触发someObject的set方法,将新赋值的数据变成响应式的
响应式删除
Vue.delete(target,属性名/索引)
this.$delete(target,属性名/索引)
代码示例:
if(food.count)
{
food.count++;
}else{
Vue.set(food,'count',1); //让对象新增的数据能够被vue数据绑定,动态更新
}
<template>
<div id="app">
<div>
<input type="text"/>
<ul>
<li v-for='(item,index) in arr' :key='index' @click="clc(index)">
<input type='checkbox' :checked='arr[index]'>
<!-- item.done -->
内容+{{index}}
</li>
<button class='b' @click='c1'>全部</button>
<button class='b' @click='c2'>未完成</button>
<button class='b' @click='c3'>已完成</button>
</ul>
</div>
<div class='btn'>
<button>提交</button>
</div>
</div>
</template>
<script>
import Vue from 'vue'
export default {
data(){
return{
// arr:[{done:false},{done:false},{done:false},{done:false},{done:false}],
arr:[false,false,false,false,false],
index2:0,
flag:false
}
},
methods: {
clc(index=0)
{
console.log(index);
Vue.set(this.arr,index, !this.arr[index])
}
},
components: {
}
}
</script>
<style>
#app{
display: flex;
}
#app>div{
flex: 3;
height: 30px;
margin-right: 20px;
}
#app>div>input{
height: 30px;
width: 100%;
}
#app>div>ul>li{
list-style: none;
height: 30px;
width: 100%;
border: solid 1px #ccc;
line-height: 30px;
}
.btn>button{
flex:1;
width: 120px;
height: 40px;
background-color:#0C8AFF;
border: none;
border-radius: 5px;
color: white;
}
.b{
width: 120px;
height: 40px;
background-color:#0C8AFF;
border: none;
border-radius: 5px;
color: white;
margin-right: 20px;
}
</style>