因此,如果 api 呼叫回傳狀態 422,我試圖將用戶重定向到不同的路由。但我收到錯誤
TypeError: Cannot read properties of undefined (reading '$router')
我的路線.js:
{
path: '/dashboard',
component: Dashboard,
name: 'Dashboard',
beforeEnter: (to, form, next) =>{
axios.get('/api/authenticated')
.then(()=>{
next();
}).catch(()=>{
return next({ name: 'Login'})
})
},
children: [
{
path: 'documentCollections',
component: DocumentCollection,
name: 'DocumentCollections'
},
{
path: 'document',
component: Document,
name: 'Document'
},
{
path: 'createDocument',
component: CreateDocument,
name: 'CreateDocument'
},
{
path: 'suppliers',
component: Suppliers,
name: 'Suppliers'
},
{
path: 'settings',
component: Settings,
name: 'Settings'
},
]
}
我也有登錄/注冊組件,當我使用
this.$router.push({ name: "DocumentCollections"});
它重定向用戶沒有任何錯誤。問題是當我在儀表板組件的子組件中時。
在 documentCollections 組件中,我有一個方法:
loadCollections(){
axios.get('/api/documentCollections')
.then((response) => {
this.Collections = response.data.data
this.disableButtons(response.data.data);
})
.catch(function (error){
if(error.response.status === 422){
//here is where the error happens
this.$router.push({ name: "Settings"});
}
});
},
這會加載集合,但如果用戶有一些資料集 null api 回傳狀態 422。我希望他被重定向到設定組件。(documentCollection 和 Settings 都是 Dashboard 的子組件)
為什么 this.$router.push 在這里不起作用,但在登錄/注冊組件中起作用?
uj5u.com熱心網友回復:
呼叫this回呼函式內部創建一個新的結合this物件,而不是在常規的函式運算式Vue的物件。
您可以使用箭頭語法來定義函式,因此this不會被覆寫。
.catch((error) => {
if(error.response.status === 422){
this.$router.push({name: "Settings"});
}
})
更多資訊
另外一個選項
this在 axios 呼叫之前定義另一個實體,并在收到回應后使用它。
let self = this
...
self.$router.push({name: "Settings"})
用你的代碼
loadCollections(){
let self = this;
axios.get('/api/documentCollections')
.then((response) => {
this.Collections = response.data.data
this.disableButtons(response.data.data);
})
.catch(function (error){
if(error.response.status === 422){
self.$router.push({name: "Settings"});
}
});
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332930.html
