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调用:

相关推荐
曹牧23 分钟前
C#:记录日志
服务器·前端·c#
小飞侠在吗26 分钟前
Vue customRef
前端·javascript·vue.js
雪碧聊技术41 分钟前
登录页【电影画风视频背景】实现
vue.js·视频背景·video标签
xhxxx1 小时前
别再让 AI 自由发挥了!用 LangChain + Zod 强制它输出合法 JSON
前端·langchain·llm
指尖跳动的光1 小时前
判断页签是否为活跃状态
前端·javascript·vue.js
用泥种荷花1 小时前
【前端学习AI】大模型调用实战
前端
Lan.W1 小时前
element UI + vue2 + html实现堆叠条形图 - 横向分段器
前端·ui·html
FAQEW1 小时前
若依(RuoYi-Vue)单体架构实战手册:自定义业务模块全流程开发指南
前端·后端·架构·若依二开
神算大模型APi--天枢6462 小时前
合规与高效兼得:国产全栈架构赋能行业大模型定制,从教育到工业的轻量化落地
大数据·前端·人工智能·架构·硬件架构
千寻girling2 小时前
马上元旦节了,手写一个《前端脚手架》庆祝一下 !
前端