溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue中this.$set如何為data中某一對象添加一個屬性

發(fā)布時間:2021-08-30 16:02:22 來源:億速云 閱讀:122 作者:小新 欄目:編程語言

小編給大家分享一下Vue中this.$set如何為data中某一對象添加一個屬性,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

項目開發(fā)的過程中,經(jīng)常會遇到這種情況:為data中的某一個對象添加一個屬性以后,但是視圖層并沒有更新該數(shù)據(jù)。如 :

    <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:{}
	        }
	}

如上所示, 切換swiper時, 發(fā)現(xiàn)雖然對象 listCatchData[index] 已經(jīng)對應了不同組的數(shù)據(jù),但是視圖層并沒有更新該數(shù)據(jù),是什么造成的呢?這是由于受JavaScript的限制,vue.js不能監(jiān)聽對象屬性的添加和刪除,因為在vue組件初始化的過程中,會調用getter和setter方法,所以你添加的屬性必須已經(jīng)存在于data中,視圖層才會響應該數(shù)據(jù)的變化。

那我們?nèi)绾问箆ue實例 data里的對象添加某一屬性后,視圖層也會更新該數(shù)據(jù)呢?

解決方發(fā):

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);//這時發(fā)現(xiàn)該對象已經(jīng)出現(xiàn)了getter與setter方法
        }

2.  Object.assign(target, sources)方法

        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)
        }

通過這兩種方式為對象添加屬性之后,他的對象身上多了get和set方法,所以,此時我們再次操作該屬性的時候,就會引起視圖的更新。

Vue中this.$set如何為data中某一對象添加一個屬性

以上是“Vue中this.$set如何為data中某一對象添加一個屬性”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

vue
AI