在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>