见如下代码,我在main.js中加了一个全局鉴权的模块,如果服务器反馈鉴权失败,希望将路由跳转的登录页面(login)。
但useRouter部分报错:
[Vue warn]: inject() can only be used inside setup() or functional components.
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')
不知道如何解决,请各位大佬指教,感谢。
完整代码:
[JavaScript] 纯文本查看 复制代码 import { createApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import cloudbase from "@cloudbase/js-sdk";
import CKEditor from '@ckeditor/ckeditor5-vue';
import './assets/main.css';
import 'element-plus/theme-chalk/index.css';
import App from './App.vue';
import router from './router';
const app = createApp(App);
const cloudbaseApp = cloudbase.init({ env: 'your-env' });
await cloudbaseApp.auth().anonymousAuthProvider().signIn().then(() => {
console.log('成功连接云端')
});
app.use(ElementPlus);
app.use(createPinia());
app.use(router);
app.use(CKEditor);
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.mount('#app');
import { ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
const cloudbaseFunction = async (e) => {
const userStore = useUserStore();
const { target, data } = e;
const callCloud = await cloudbase.callFunction({
name: 'webCloud',
data: {
target,
userPhoneNumber: userStore.user.phoneNumber + '1',
userToken: userStore.token,
data
}
})
console.log('[callCloud]', callCloud.result);
if (callCloud.result.isAuthNoPass) {
const router = useRouter();
ElMessageBox.alert('自动鉴权不通过,请重新登录', '权限异常', {
type: 'error',
confirmButtonText: '好的',
'show-close': false,
callback: (action) => {
userStore.toLogOut();
router.push({ name: 'login' })
},
})
return;
}
return callCloud;
}
app.provide('global', { cloudbase: cloudbaseApp, cloudbaseFunction }); |