通过数组的变异方法我们可以让视图随着数据变化而变化。但vue 不能检测对象属性的添加或删除,即如果操作对象数据变化,视图是不会随着对象数据变化而变化的。使用vue.set()可以帮助我们解决这个问题。
需求:可多选的列表:
初始代码:准备好的数据: tag: [ { name: 马化腾 }, { name: 马云 }, { name: 刘强东 }, { name: 李彦宏 }, { name: 比尔盖茨 }, { name: 扎克伯格 } ],
template&css:<p class="choice-tag"> <ul class="d-f fd-r jc-fs ai-c fw-w"> //梦想通过判断每个item的checked的布尔值来决定选中或未选中 <li :class="tag[index].checked == true? 'choice-tag-check':''" v-for="(item,index) in tag" :key="item.id" @click="choicetagfn(index)"> {{item.name}} </li> </ul></p>.choice-tag-check{ border: 1px solid #2d8cf0 !important; color: #2d8cf0 !important;}
一开始的想法是将静态数据(或网络请求的数据)添加一个新的字段,通过修改checked为true或false来判断选中状态。
mounted() { for(let i = 0 ; i
都添加上了,感觉一切顺利,有点美滋滋。
选择方法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:<p class="choice-tag"> <ul class="d-f fd-r jc-fs ai-c fw-w"> <li :class="tagcheck[index] == true? 'choice-tag-check':''" v-for="(item,index) in tag" :key="item.id" @click="choicetagfn(index)"> {{item.name}} </li> </ul></p>
新的选择方法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 ) }},
就大功告成啦实现了列表多选,视图会根据数据(数组,对象)的变化而变化。
相关推荐:
vue制作图片轮播
vue如何操作静态图片和网络图片
zend framework 视图中使用视图
thinkphp框架之视图
以上就是vue.set如何实现视图随着对象修改而动态变化(可多选)的详细内容。