Vue [__ob__: Observer]取不到值問題的解決


產生原因

如果從后端返回過來的數組數據,進行遍歷的時候不在success回調函數內,則會產生如下的數據格式,雖然其也是數組格式,但是內部的值取不出來,給后台也傳不過去。

[__ob__: Observer]
0: "http://localhost:5757/userImages/o-WF75fylWJY6vm_xRNYeNIpicOg/2020032123451074033.jpg"
1: "http://localhost:5757/userImages/o-WF75fylWJY6vm_xRNYeNIpicOg/2020032123451034889.jpg"
length: 2
nv_length: (...)
__ob__: Observer {value: Array(2), dep: Dep, vmCount: 0}
__proto__: Array

原因:其實跟__ob__: Observer這個屬性沒有多少關系,原因還是在於異步,因為wx.chooseImage是一個異步執行的函數,如果在另外一個函數中直接取得tempfileList的值進行遍歷的話,就會造成等不到回調結束就完成遍歷,所以在數組中__ob__: Observer屬性雖然監聽到了值,但是取不出來。

chooseImg(){
  var that = this
  wx.chooseImage({
	sizeType: ['compressed'],
        sourceType: ['album', 'camera'],			    
	count:3,
	success:(res)=>{
		console.log(res)
		that.tempfileList = res.tempFilePaths
	}
  })
}
submitImg(filePath){
   ......
}
submit(){
   this.tempfileList.map((item)=>{
	that.submitImgs(item)
   })
}

解決辦法

要在回調函數內進行遍歷,這樣回調函數返回數組數據的順序和執行遍歷的順序就會一致,因此就不存在異步操作所產生的問題

chooseImg(){
  var that = this
  wx.chooseImage({
	sizeType: ['compressed'],
        sourceType: ['album', 'camera'],			    
	count:3,
	success:(res)=>{
		console.log(res)
		that.tempfileList = res.tempFilePaths
                that.tempfileList.map((item)=>{
                       that.submitImg(item)
                })
	}
  })
}
submitImg(filePath){
   ......
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM