VUE3,在main.js中调用路由(useRouter )的问题
见如下代码,我在main.js中加了一个全局鉴权的模块,如果服务器反馈鉴权失败,希望将路由跳转的登录页面(login)。但useRouter部分报错:
: inject() can only be used inside setup() or functional components.
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')
不知道如何解决,请各位大佬指教,感谢。
完整代码:
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 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.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 }); 本帖最后由 cqwcns 于 2023-1-28 10:47 编辑
打印了一下变量,是这样的:
console.log('useRouter', useRouter)
// useRouter f useRouter() {
// return inject(routerKey);
// }
const router = useRouter();
console.log('router', router)\
// router undefined 这个错误提示很明显了,断点调试下看看为什么router是undefined 你的inject要放在Vue组件里(主要指setup()里),你可能放在普通代码里了 本帖最后由 水到渠成的执着 于 2023-1-28 13:53 编辑
import router from "@/router/index";
router.push("/login");
页:
[1]