在vue3+uniapp+vite中挂载全局属性方法

在vue3+uniapp+vite中挂载全局this属性

背景

vue3中【CompositionAPI】已经全面禁用this,导致没办法直接使用this。

旧版的【OptionsAPI 】还能继续使用this挂载的方法

方式一

挂载

javascript 复制代码
# 在main.js 中定义相关数据信息
import { createSSRApp } from 'vue'
import BluetoothUtils from "@/plugin/BluetoothUtils";
export function createApp() {
  const app = createSSRApp(App)
  // 全局挂载
  app.config.globalProperties.$BluetoothUtils = BluetoothUtils
  return {
    app
  }
}

使用

javascript 复制代码
<script setup>
	import { ref, onMounted, getCurrentInstance, inject } from 'vue'
	const {proxy} = getCurrentInstance()
	console.log(proxy.$BluetoothUtils, 44444)// 通过 proxy 调用
</script>

方式二

挂载

javascript 复制代码
# 在main.js 中定义相关数据信息
import { createSSRApp } from 'vue'
import BluetoothUtils from "@/plugin/BluetoothUtils";
export function createApp() {
  const app = createSSRApp(App)
   // 全局挂载到provide
   app.provide('$BluetoothUtils', BluetoothUtils)
  return {
    app
  }
}

使用

javascript 复制代码
<script setup>
import { ref, onMounted, getCurrentInstance, inject } from 'vue'
const bluetoothUtils = inject('$BluetoothUtils')
console.log(bluetoothUtils,555)
</script>

旧版 【OptionsAPI 】

需要配合【方式一】的挂载方法

javascript 复制代码
<script>
	export default {
		onLaunch: function() {
			console.log(this.$BluetoothUtils,'onLaunch')
		},
		onShow: function() {
			console.log('App Show');
		},
		onHide: function() {
			console.log('App Hide')
		},

		methods: {
			test() {
				console.log(this.$BluetoothUtils,'methods')
			}
	}
</script>
相关推荐
2601_949480065 小时前
【无标题】
开发语言·前端·javascript
css趣多多5 小时前
Vue过滤器
前端·javascript·vue.js
●VON5 小时前
React Native for OpenHarmony:项目目录结构与跨平台构建流程详解
javascript·学习·react native·react.js·架构·跨平台·von
爱吃大芒果6 小时前
Flutter for OpenHarmony 实战:mango_shop 路由系统的配置与页面跳转逻辑
开发语言·javascript·flutter
qq_177767376 小时前
React Native鸿蒙跨平台实现消息列表用于存储所有消息数据,筛选状态用于控制消息筛选结果
javascript·react native·react.js·ecmascript·harmonyos
沐雪架构师6 小时前
LangChain 1.0 Agent开发实战指南
开发语言·javascript·langchain
2501_940007896 小时前
Flutter for OpenHarmony三国杀攻略App实战 - 战绩记录功能实现
开发语言·javascript·flutter
摘星编程6 小时前
React Native + OpenHarmony:自定义useEllipsis省略号处理
javascript·react native·react.js
Rysxt_6 小时前
UniApp获取安卓系统权限教程
android·uni-app
这是个栗子7 小时前
【Vue代码分析】前端动态路由传参与可选参数标记:实现“添加/查看”模式的灵活路由配置
前端·javascript·vue.js