在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>
相关推荐
摸鱼的春哥1 小时前
Agent教程15:认识LangChain,Agent框架的王(上)
前端·javascript·后端
明月_清风2 小时前
自定义右键菜单:在项目里实现“选中文字即刻生成新提示”
前端·javascript
明月_清风2 小时前
告别后端转换:高质量批量导出实战
前端·javascript
刘发财7 小时前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
ssshooter14 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live0000015 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉15 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
球球pick小樱花15 小时前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
前端Hardy16 小时前
干掉 Virtual DOM?尤雨溪开始"强推" Vapor Mode?
vue.js·vue-router