學習uni-app新手小白最容易犯的錯誤--------(this指向問題)

學習uni-app新手小白最容易犯的錯誤(一)

在uni-app中有很多像下面這樣的API都是封裝好的,對我們來說非常簡單。

uni.getSystemInfo({
				success: function(res) {
					// console.log(res)
					
				}
			})

下面我說的這一點新手小白門往往都會踩的坑~~~~~~~~~~仔細看哦
下面代碼就是在進入界面時獲取你使用手機屏幕的代碼,現在這裏面是有錯誤的,這樣使用是獲取不到屏幕高度的,因爲裏面this指向改變了。(可以在代碼中加入**console.log(this)**檢查一下看看this返回是什麼值)

onLoad() {
			console.log(this)
			uni.getSystemInfo({
			console.log(this)
				success: function(res) {
				console.log(this// console.log(res)
					this.windowHeight = res.windowHeight;
				}
			})
		},

下面就給大家奉上解決方法

onLoad() {
			let _this = this
			uni.getSystemInfo({
				success: function(res) {
					// console.log(res)
					_this.windowHeight = res.windowHeight;
				}
			})
		},

在最外面吧this賦值給一個變量,在函數中直接用變量當做this使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章