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

相关推荐
用户69371750013849 小时前
Google 正在“收紧侧加载”:陌生 APK 安装或需等待 24 小时
android·前端
蓝帆傲亦9 小时前
Web 前端搜索文字高亮实现方法汇总
前端
用户69371750013849 小时前
Room 3.0:这次不是升级,是重来
android·前端·google
漫随流水10 小时前
旅游推荐系统(view.py)
前端·数据库·python·旅游
踩着两条虫11 小时前
VTJ.PRO 核心架构全公开!从设计稿到代码,揭秘AI智能体如何“听懂人话”
前端·vue.js·ai编程
jzlhll12312 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin
用头发抵命13 小时前
Vue 3 中优雅地集成 Video.js 播放器:从组件封装到功能定制
开发语言·javascript·ecmascript
蓝冰凌13 小时前
Vue 3 中 defineExpose 的行为【defineExpose暴露ref变量】详解:自动解包、响应性与实际使用
前端·javascript·vue.js
奔跑的呱呱牛13 小时前
generate-route-vue基于文件系统的 Vue Router 动态路由生成工具
前端·javascript·vue.js