在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>
相关推荐
peak_chan1 分钟前
通过vue-virtual-scroller封装虚拟滚动el-select
前端·javascript·vue.js
小李子呢021110 分钟前
前端八股Vue(7)---computed计算属性和watch侦听器
前端·javascript·vue.js
吴声子夜歌19 分钟前
ES6——对象的扩展详解
开发语言·javascript·es6
Ruihong1 小时前
Vue3 转 React:组件透传 Attributes 与 useAttrs 使用详解|VuReact 实战
vue.js·react.js
gwjcloud1 小时前
基于linux下docker部署前端vue项目
前端·javascript·vue.js
小李子呢02112 小时前
前端八股Vue(6)---v-if和v-for
前端·javascript·vue.js
程序员buddha2 小时前
ES6 迭代器与生成器
前端·javascript·es6
aq55356002 小时前
网页开发四剑客:HTML/CSS/JS/PHP全解析
javascript·css·html
程序员buddha2 小时前
TypeScript详细教程
javascript·ubuntu·typescript
周星星日记3 小时前
vue3中静态提升和patchflag实现
前端·vue.js·面试