嗨,我有一個現有的專案,我們action.js正在派遣logoutFromServer401 Unauthorized
這是它的樣子
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:無法讀取未定義的屬性(讀取“推送”)
對于下面的代碼
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 路由
請幫助我提前謝謝!
uj5u.com熱心網友回復:
您可以顯式匯入路由器并使用它。
==> 路由器.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},
...
]
})
===> 動作.js
import {router} from "../router.js"
export const someAction = ({commit}) => {
router.push("/");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/434624.html
