在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>
相关推荐
38242782711 小时前
JS表单提交:submit事件的关键技巧与注意事项
前端·javascript·okhttp
于是我说11 小时前
Vue3 的 CompositionAPI 相较于 OptionsAPI,主要优势和适用场景有哪些
vue.js
VX:Fegn089511 小时前
计算机毕业设计|基于springboot + vue智慧养老院管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
interception11 小时前
js逆向之京东原型链补环境h5st
javascript·爬虫·网络爬虫
木土雨成小小测试员11 小时前
Python测试开发之前端二
javascript·python·jquery
全栈小511 小时前
【前端】在JavaScript中,=、==和===是三种不同的操作符,用途和含义完全不同,一起瞧瞧
开发语言·前端·javascript
如果你好12 小时前
Vue createRenderer 自定义渲染器从入门到实战
前端·javascript·vue.js
小高00712 小时前
读懂 Tailwind v4:为什么它是现代前端项目的必选项?
前端·javascript·vue.js
boooooooom12 小时前
computed、watch 与 watchEffect 的使用边界与实战指南
javascript·vue.js
冰暮流星12 小时前
javascript短路运算
开发语言·前端·javascript