cqwcns 发表于 2022-4-17 19:49

vue3全局变量的问题

Vue3应用开发,后端使用的是腾讯云开发,需要云开发SDK。


引入的代码是这样的,main.js:
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'

// SDK引入
import cloudbase from "@cloudbase/js-sdk";
const tcb = cloudbase.init({
    env: "hello996c"
});

// SDK使用
// const auth = tcb.auth();
// async function login() {
//   await auth.anonymousAuthProvider().signIn();
//   const loginState = await auth.getLoginState();
//   console.log(loginState);
// }
// login();

createApp(App).use(ElementPlus).use(router).mount('#app')

整个应用要频繁用到这个SDK,所以我希望一次引入到全局,其他JS直接调用。
我尝试将main.js改为:
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'

// 引入SDK
import cloudbase from "@cloudbase/js-sdk";
const tcb = cloudbase.init({
    env: "hello996c"
});
// 挂到全局变量
App.config.globalProperties.$tcb = tcb;

createApp(App).use(ElementPlus).use(router).mount('#app')


尝试在login中引用:
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();

console.log(proxy)

const tcb = proxy.$tcb

const auth = tcb.auth();

export async function login() {
    console.log('匿名登录')
    await auth.anonymousAuthProvider().signIn();
    const loginState = await auth.getLoginState();
    console.log(loginState);
}


结果报错:
Uncaught TypeError: Cannot destructure property 'proxy' of '(0 , vue__WEBPACK_IMPORTED_MODULE_0__.getCurrentInstance)(...)' as it is null.
    at eval (login.js?34c9:2:1)
    at Module../src/api/login.js (app.js:74:1)
    at __webpack_require__ (app.js:358:33)
    at fn (app.js:626:21)
    at eval (index.js??clonedRuleSet-40.use!./node_modules/vue-loader/dist/index.js??ruleSet.use!./src/views/HomeView.vue?vue&type=script&setup=true&lang=js:3:68)
    at Module../node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use!./node_modules/vue-loader/dist/index.js??ruleSet.use!./src/views/HomeView.vue?vue&type=script&setup=true&lang=js (app.js:30:1)
    at __webpack_require__ (app.js:358:33)
    at fn (app.js:626:21)
    at eval (HomeView.vue?vue&type=script&setup=true&lang=js:5:222)
    at Module../src/views/HomeView.vue?vue&type=script&setup=true&lang=js (app.js:184:1)


好像是login.js无法获得这个全局变量,不知道怎么改,求指教,感谢。

unmask 发表于 2022-4-17 21:00

本帖最后由 unmask 于 2022-4-17 21:17 编辑

getCurrentInstance尽量在setup之后再调用,不要在全局代码执行,很有可能当前对象还没有实例化。
你的代码也就是在login()内部再调用。
试试下面这个,没有验证过。
const {appContext: {config: {globalProperties}}} = getCurrentInstance()
const auth = globalProperties.$tcb.auth();
页: [1]
查看完整版本: vue3全局变量的问题