uni-app的 js API 回调函数this指向问题,导致视图层没有更新

背景

        一开始以为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>

上述代码运行结果如下图

看一下内外层this指的是什么?

解决方案

1、箭头函数

        修改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')
	}
});
2、定义变量

        用一个变量把外层的this存储起来,回调函数要用到外层this就用该变量。

onLoad() {
	this.title = 'Hello world'
	var that = this
	uni.getSystemInfo({
		success: function (res) {
			that.height = res.windowHeight
			that.appName = 'this指向问题'
		}
	});
},

最后记得开启失去焦点自动保存 

  • 18
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值