通过数组的变异方法我们可以让视图随着数据变化而变化。但Vue 不能检测对象属性的添加或删除,即如果操作对象数据变化,视图是不会随着对象数据变化而变化的。使用Vue.set()可以帮助我们解决这个问题。
需求:
初始代码:
准备好的数据:
tag: [
{ name: "马化腾" },
{ name: "马云" },
{ name: "刘强东" },
{ name: "李彦宏" },
{ name: "比尔盖茨" },
{ name: "扎克伯格" }
],
template&CSS:
//梦想通过判断每个item的checked的布尔值来决定选中或未选中
-
{{item.name}}
.choice-tag-check{
border: 1px solid #2d8cf0 !important;
color: #2d8cf0 !important;
}
一开始的想法是将静态数据(或网络请求的数据)添加一个新的字段,通过修改checked为true或false来判断选中状态。
mounted() {
for(let i = 0 ; i
console.log(this.tag)一下
都添加上了,感觉一切顺利,有点美滋滋。
选择方法methods:
//选择标签
choiceTagFn(index) {
if(this.tag[index].checked === false){
this.tag[index].checked = true
}else{
this.tag[index].checked = false
}
},
随便选两个,然后再console.log(this.tag)一下
数据层tag的checked值已经发生改变,然鹅~~~
查阅文档后找到了原因:由于 JavaScript 的限制,Vue 不能检测对象属性的添加或删除
那怎么办?官方的说法是:对于已经创建的实例,Vue 不能动态添加根级别的响应式属性。但是,可以使用 Vue.set(object, key, value) 方法向嵌套对象添加响应式属性。
今天的主角就是:Vue.set()
Vue.set( object, key, value )
object:需要更改的数据(对象或者数组)
key:需要更改的数据
value :重新赋的值
更改后的代码
我们不再使用for来给对象添加字段,而是使用一个新的数组来展示选中与未选中状态
新的数据:
tag: [
{ name: "马化腾" },
{ name: "马云" },
{ name: "刘强东" },
{ name: "李彦宏" },
{ name: "比尔盖茨" },
{ name: "扎克伯格" }
],
//是否选中
tagCheck:[false,false,false,false,false,false],
我们就不再直接操作数据,而是操作新的数组
新的template&CSS:
-
{{item.name}}
新的选择方法methods:
我们可以使用this.$set来代替Vue.set
//选择标签
choiceTagFn(index) {
if(this.tagCheck[index] === false){
//(更改源,更改源的索引,更改后的值)
this.$set( this.tagCheck, index, true )
}else{
//(更改源,更改源的索引,更改后的值)
this.$set( this.tagCheck, index, false )
}
},
就大功告成啦实现了列表多选,视图会根据数据(数组,对象)的变化而变化。