在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>
相关推荐
遇见很ok1 天前
Web Worker
前端·javascript·vue.js
elangyipi1231 天前
JavaScript 高级错误处理与 Chrome 调试艺术
开发语言·javascript·chrome
前端不太难1 天前
RN Navigation vs Vue Router:从架构底层到工程实践的深度对比
javascript·vue.js·架构
暴富暴富暴富啦啦啦1 天前
Map 缓存和拿取
前端·javascript·缓存
天问一1 天前
前端Vue使用js-audio-plugin实现录音功能
前端·javascript·vue.js
00后程序员张1 天前
fastlane 结合 appuploader 命令行实现跨平台上传发布 iOS App
android·ios·小程序·https·uni-app·iphone·webview
小魏的马仔1 天前
【elementui】el-date-picker日期选择框,获取焦点后宽度增加问题调整
前端·vue.js·elementui
代码不停1 天前
前端基础知识
javascript·css·html
山风wind1 天前
设计模式-单例模式详解
开发语言·javascript·ecmascript