Vue3应用开发,后端使用的是腾讯云开发,需要云开发SDK。
引入的代码是这样的,main.js:
[JavaScript] 纯文本查看 复制代码 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改为:
[JavaScript] 纯文本查看 复制代码 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中引用:
[JavaScript] 纯文本查看 复制代码 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[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./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[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./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无法获得这个全局变量,不知道怎么改,求指教,感谢。 |