您好,欢迎来到吉趣旅游网。
搜索
您的当前位置:首页Vue.set如何实现视图随着对象修改而动态变化(可多选)

Vue.set如何实现视图随着对象修改而动态变化(可多选)

来源:吉趣旅游网
本篇文章给大家带来的内容是关于Vue.set如何实现视图随着对象修改而动态变化(可多选),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

通过数组的变异方法我们可以让视图随着数据变化而变化。但Vue 不能检测对象属性的添加或删除,即如果操作对象数据变化,视图是不会随着对象数据变化而变化的。使用Vue.set()可以帮助我们解决这个问题。

需求:

可多选的列表:

534673353-5b729d61d62f8_articlex.png

341431037-5b729f3ee02b8_articlex.png

初始代码:

准备好的数据:

 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<this.tag.length;i++){
 this.tag[i].checked = false
 }
}

console.log(this.tag)一下

1552927370-5b72a3040f089_articlex.png

都添加上了,感觉一切顺利,有点美滋滋。

选择方法methods:

 //选择标签
choiceTagFn(index) {
 if(this.tag[index].checked === false){
 this.tag[index].checked = true
 }else{
 this.tag[index].checked = false
 }
},

随便选两个,然后再console.log(this.tag)一下

1742743632-5b72a4f655e2b_articlex.png

数据层tag的checked值已经发生改变,然鹅~~~

534673353-5b729d61d62f8_articlex.png

视图层是一动不动,说好的响应式呢?

查阅文档后找到了原因:由于 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 )
 }
},

就大功告成啦实现了列表多选,视图会根据数据(数组,对象)的变化而变化。

Copyright © 2019- jqkq.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务