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

相关推荐
Byron070716 小时前
Vue 中使用 Tiptap 富文本编辑器的完整指南
前端·javascript·vue.js
css趣多多17 小时前
地图快速上手
前端
zhengfei61117 小时前
面向攻击性安全专业人员的一体化浏览器扩展程序[特殊字符]
前端·chrome·safari
码丁_11717 小时前
为什么前端需要做优化?
前端
Mr Xu_17 小时前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构
Byron070718 小时前
从 0 到 1 搭建 Vue 前端工程化体系:提效、提质、降本实战落地
前端·javascript·vue.js
哆啦code梦18 小时前
前端存储三剑客:localStorage、sessionStorage与Cookie解析
前端·前端存储
zhengfei61118 小时前
【AI平台】- 基于大模型的知识库与知识图谱智能体开发平台
vue.js·语言模型·langchain·知识图谱·多分类
徐小夕@趣谈前端18 小时前
Web文档的“Office时刻“:jitword共建版2.0发布!让浏览器变成本地生产力
前端·数据结构·vue.js·算法·开源·编辑器·es6
Data_Journal18 小时前
如何使用 Python 解析 JSON 数据
大数据·开发语言·前端·数据库·人工智能·php