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中修改后的诗圣。