? ? ? ? 一开始以为uni-app视图层更新跟微信小程序一样要setData,结果没忘记了this指向,想了一会为什么?被自己蠢到了!!!
????????title变量没有问题,而height和appName变量显示效果都不对
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<view>{{height}} px</view>
<view>{{appName}}</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
height: 0,
appName: 'test'
}
},
onLoad() {
this.title = 'Hello world'
uni.getSystemInfo({
success: function (res) {
this.height = res.windowHeight
console.log(this.height,'test1')
this.appName = 'this指向问题'
console.log(this.appName,'test2')
}
});
},
methods: {
}
}
</script>
上述代码运行结果如下图
解决方案
? ? ? ? 修改uniapp的js API回调函数为箭头函数,如下
uni.getSystemInfo({
success: (res) => {
console.log(this,'内this test');
this.height = res.windowHeight
console.log(this.height,'test1')
this.appName = 'this指向问题'
console.log(this.appName,'test2')
}
});
? ? ? ? 用一个变量把外层的this存储起来,回调函数要用到外层this就用该变量。
onLoad() {
this.title = 'Hello world'
var that = this
uni.getSystemInfo({
success: function (res) {
that.height = res.windowHeight
that.appName = 'this指向问题'
}
});
},