在Uniapp如何设置全局变量

1.在uniapp中,

// App.vue
export default {
	globalData: {
        db_picture: 'https://testimg.xxxxx.com/',
	    uploadUrl: 'https://test.xxxxx.com',
		userName: '白居易'
	},
	// 这里需要注意的是,如果我们需要在App.vue中使用userName
	// 使用getApp().globalData.userName是不行,因为此时getApp()尚未生成
	// 1. 非V3模式,可以通过this.$scope.globalData获取
	// 2. V3模式,可以通过getApp({allowDefault: true}).globalData获取
	// 详见uni-app文档:https://uniapp.dcloud.io/collocation/frame/window?id=getapp
	onLaunch() {
		console.log(this.$scope.globalData.userName);
	}
}

2.定义好了globalData,我们进入A.vue,并使用userName值

<!-- A.vue -->
 
<template>
	<view>
		<!-- 注意,不能在模板中直接使用 getApp().globalData.userName -->
		<<琵琶行>>的作者是:{{author}}
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				author: ''
			}
		},
		onShow() {
			// 每次A.vue出现在屏幕上时,都会触发onShow,从而更新author值
			this.author = getApp().globalData.userName;
		}
	}
</script>

3.当我们从A.vue进入B.vue时,引用并修改userName的值

<!-- B.vue -->
 
<template>
	<view>
		<view>
			<!-- 注意,不能在模板中直接使用 getApp().globalData.userName -->
			<<卖炭翁>>的作者是:{{author}}
		</view>
		<view>
			<u-button @click="modifyUserName">修改userName值</u-button>
		</view>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				author: ''
			}
		},
		onShow() {
			// 每次B.vue出现在屏幕上时,都会触发onShow,从而更新author值
			this.author = getApp().globalData.userName;
		},
		methods: {
			modifyUserName() {
				getApp().globalData.userName = "诗圣";
				// 修改userName后,本页的author依然不会自动刷新,因为globalData不是响应式的
				// 我们仍然需要手动刷新本页的author值,由此可见globalData的弊端
				this.author = getApp().globalData.userName;
			}
		}
	}
</script>

4.假设我们从B.vue返回A.vue,这时A.vue出现在屏幕上,触发了它的onShow生命周期,执行了this.author = getApp().globalData.userName;, 因而我们可以看到A.vue的值由白居易变成了在B.vue中修改后的诗圣。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zsxy2019

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值