Uniapp Vue2 Vue3常量保存及调用

在Vue2中,保存全局变量都是在APP.vue中,如下:

调用的话直接调用如下:

一、对于自定义的globalData,需要在APP.vue声明,然后页面中调用const app = getApp();,然后使用app.globalData.xxx获取,如下:

二、对于Vue.prototype里面的数据,直接调用this.xxx调用:

在Vue3中,全局变量有变化如下:

一、对于自定义的globalData和vue2中声明及调用方式不变,需要在页面中调用const app = getApp();,然后使用app.globalData.xxx获取,如下:

二、对于Vue.prototype里面的数据,需要在main.js初始化:

复制代码
import App from './App'

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	...App
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
export function createApp() {
	const app = createSSRApp(App)
	app.config.globalProperties.statusHeight = uni.getWindowInfo().statusBarHeight;
	app.config.globalProperties.windowWidth = uni.getWindowInfo().windowWidth;
	app.config.globalProperties.safeAreaTop = uni.getWindowInfo().safeArea.top;
	app.config.globalProperties.windowHeight = uni.getWindowInfo().windowHeight;
	app.config.globalProperties.isUpiPhoneX = false;
	const safeAreaBottom = uni.getWindowInfo().screenHeight - uni.getWindowInfo().safeArea.bottom
	const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
	// app.config.globalProperties.navHeight = menuButtonInfo.bottom + menuButtonInfo.top - e
	// 	.statusBarHeight;
	app.config.globalProperties.navHeight = (menuButtonInfo.top - uni.getWindowInfo().statusBarHeight) * 2 +
		menuButtonInfo.height + uni.getWindowInfo().statusBarHeight
	app.config.globalProperties.menuTop = menuButtonInfo.top;
	app.config.globalProperties.menuHeight = menuButtonInfo.height;
	app.config.globalProperties.isiPhoneX = safeAreaBottom == 34 ? true : false;
	// app.config.globalProperties.isiPhone11Pro = uni.getDeviceInfo().model.includes('iPhone 11 Pro') ? true : false;
	app.config.globalProperties.safeAreaBottom = safeAreaBottom;
	return {
		app
	}
}
// #endif

界面可以直接调用,js中需要声明一下getCurrentInstance参数,如下:

①界面调用:

②js调用:

相关推荐
铁皮饭盒7 小时前
Bun执行python代码
前端·javascript·后端
hunterandroid7 小时前
Service 与前台服务:让任务在后台持续运行
前端
米饭同学i7 小时前
深扒 LobsterAI 官网前端动效实现方案:从交互细节到代码实践
前端
前端啊7 小时前
告别 el-table 打印难题,vue3-print-el-table 来了!
前端·vue.js
JarvanMo7 小时前
AI时代跨平台还有必要吗?
前端
Patrick_Wilson8 小时前
幂等到底是什么?从前端视角讲透 SQL、HTTP 与 POST 接口的幂等设计
前端·后端·架构
凌览8 小时前
一人公司别再上 Jenkins,真不值
前端·后端
oil欧哟8 小时前
Codex 最佳实践(超级长文):先搞懂 AI,再用好 AI
前端·人工智能·后端
小小小小宇8 小时前
前端渲染方式
前端
京东云开发者9 小时前
全球首个!京东全栈开源JoyAI-VL-Interaction,让大模型从“一问一答”走向“边看边说”
前端