如何从vue中的vuex操作重定向到登录页面
How to re-direct to login page from vuex action in vue
你好,我有一个现有项目,在 action.js
中,我们在 401 Unauthorized
上调度 logoutFromServer
这是它的样子
users.action.js
async getAllUsers(context,payload={}){
try{
let resp = await axios.get(...);
}catch(error){
if(error.response.status == 401)
context.dispatch('logoutFromServer');
}
}
customers.action.js
async getAllCustomers(context,payload={}){
try{
let resp = await axios.get(...);
}catch(error){
if(error.response.status == 401)
context.dispatch('logoutFromServer');
}
}
上面的代码几乎在每个 GET,POST,PUT,DELETE
至少超过 1000 个地方重复(所以我现在无法更改它们)。 logoutFromServer
发送后,我得到
TypeError: Cannot read properties of undefined (reading 'push')
以下代码
authentication.action.js
async logoutFromServer(context){
try{
let resp = await axios.delete(...);
}catch(e){
console.log('must be already deleted');
}
//clear cookie
this.$router.push({name:"login"}) <-- here the above error occurs i,e `TypeError: Cannot read properties of undefined (reading 'push')`
}
问题:如何从vuex actions
重定向到/login路由
请帮助我提前谢谢!!
您可以显式导入路由器并使用它。
==> router.js
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
export const router = new VueRouter({
mode: 'hash',
base: "./",
routes: [
{ path: "/", component: home},
...
]
})
===> actions.js
import {router} from "../router.js"
export const someAction = ({commit}) => {
router.push("/");
}
你好,我有一个现有项目,在 action.js
中,我们在 401 Unauthorized
logoutFromServer
这是它的样子
users.action.js
async getAllUsers(context,payload={}){
try{
let resp = await axios.get(...);
}catch(error){
if(error.response.status == 401)
context.dispatch('logoutFromServer');
}
}
customers.action.js
async getAllCustomers(context,payload={}){
try{
let resp = await axios.get(...);
}catch(error){
if(error.response.status == 401)
context.dispatch('logoutFromServer');
}
}
上面的代码几乎在每个 GET,POST,PUT,DELETE
至少超过 1000 个地方重复(所以我现在无法更改它们)。 logoutFromServer
发送后,我得到
TypeError: Cannot read properties of undefined (reading 'push')
以下代码
authentication.action.js
async logoutFromServer(context){
try{
let resp = await axios.delete(...);
}catch(e){
console.log('must be already deleted');
}
//clear cookie
this.$router.push({name:"login"}) <-- here the above error occurs i,e `TypeError: Cannot read properties of undefined (reading 'push')`
}
问题:如何从vuex actions
重定向到/login路由
请帮助我提前谢谢!!
您可以显式导入路由器并使用它。
==> router.js
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
export const router = new VueRouter({
mode: 'hash',
base: "./",
routes: [
{ path: "/", component: home},
...
]
})
===> actions.js
import {router} from "../router.js"
export const someAction = ({commit}) => {
router.push("/");
}