During the project development process, we often encounter this situation: after adding an attribute to an object in the data, the view layer does not update the data. For example:
<template> <swiper class="home-swiper" :current="activeIndex" @change="change"> <swiper-item v-for="(item,index) in tab" :key="index"> <view class="swiper-item"> <listItem :list="listCatchData[index]"></listItem> </view> </swiper-item> </swiper></template>
data() { return { list: [], listCatchData:{} } }
As shown above, when switching swiper, it is found that although the object listCatchData[index] has corresponded to different groups of data, the view layer has not updated the data. What is the reason? This is due to the limitation of JavaScript. vue.js cannot monitor the addition and deletion of object properties. Because during the initialization process of the vue component, the getter and setter methods will be called, so the properties you add must already exist in the data and view layer. will respond to changes in the data. [Related recommendation: "vue.js Tutorial"]
So how do we make the view layer update the data after adding a certain attribute to the object in the vue instance data?
# solutor:
1. This. $ Set (Obj, Key, Value)
async getList(current) { const res = await this.$myRequest({ url: 'uniapi/getList', data:{catid:this.tab[current].catid} }) const {data} = res this.$set(this.listCatchData,current,data) console.log(this.listCatchData);//这时发现该对象已经出现了getter与setter方法 }
2. Object.assign (target, target, sources) method
async getList(current) { const res = await this.$myRequest({ url: 'uniapi/getList', data:{catid:this.tab[current].catid} }) const {data} = res this.listCatchData[current] = data this.listCatchData = Object.assign({},this.listCatchData) }
After adding attributes to the object through these two methods, his object has get and set methods. Therefore, when we operate the attribute again at this time, it will cause the view to be updated. .
Related recommendations:
The latest 5 vue.js video tutorial selections
The latest uni-app video tutorial recommendations in 2021 (from entry to master)
The above is the detailed content of Vue this.$set adds a property to an object in data. For more information, please follow other related articles on the PHP Chinese website!