在vue2中我们只需要引入main.js即可获取this实例,直接
this.$router.push('/login')
首先在vue3中我们使用comAPI,但是在自己封装的js里面,我们不能使用useRouter ,useRoute,他们需要在setup中调用执行后才能用,于是给出解决办法:
直接使用router实例:
import axios from 'axios'
import { ElMessage } from "element-plus";
import router from '../../router'
let Ajax = axios.create({
baseURL: "http://127.0.0.1:3003/",
timeout: 5000
})
Ajax.interceptors.response.use(response => {
if (response.data.data.code == 2) {
ElMessage(response.data.data.data)
router.push('/login')
localStorage.removeItem('username')
return []
}
return response.data;
}, error => {
return Promise.reject(error);
});
const get = (url, params) => {
Ajax.defaults.headers['token'] = localStorage.getItem('token')
return new Promise((relove, reject) => {
Ajax.get(url, { params }).then(res => relove(res)).catch(err => reject(err))
})
}
const post = (url, params) => {
Ajax.defaults.headers['token'] = localStorage.getItem('token')
return new Promise((relove, reject) => {
Ajax.post(url, params).then(res => relove(res)).catch(err => reject(err))
})
}
export default {
get, post
}
核心:
import router from '../../router'
router.push('/login')
router文件下的index.js文件就是我们的路由实例。
我们的路由文件:
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
//主页面
{
path: "/home",
component: () => import('../views/home.vue'),
redirect: '/home/userlist',
children: [
{
path: 'userlist',
component: () => import('../components/userlist.vue')
},
{
path: 'userinfo',
component: () => import('../components/userinfo.vue')
},
]
},
//登录页面
{
path: "/login",
component: () => import('../views/login.vue')
},
//直接报错
// {
// path: "*",
// redirect: "/login"
// },
//正确写法:
//1
// {
// path: "/:catchAll(.*)",
// redirect: "/login"
// },
//2
// {
// path: "/:pathMatch(.*)*",
// redirect: "/login"
// },
//3
{
path: "/:pathMatch(.*)",
redirect: "/login"
},
],
})
export default router