TypeError: Cannot read properties of undefined (reading #39;$router#39;) vuejs(TypeError:无法读取未定义(读取#39;$ROUTER#39;)vuejs的属性)
本文介绍了TypeError:无法读取未定义(读取';$ROUTER';)vuejs的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,如果API调用返回状态422,我会尝试将用户重定向到不同路由。但是我收到一个错误TypeError: Cannot read properties of undefined (reading '$router')
我的routes.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"});
它不会出现任何错误地重定向用户。问题是我在仪表板组件的子组件中。
在DocentColltions组件中,我有一个方法:
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"});
}
});
},
其加载集合,但是如果用户具有某些数据集,则返回状态422为空API。我想让他重定向到设置组件。
(document Collection和Settings都是Dashboard的子组件)
为什么.$router.ush在这里不工作,但在登录/注册组件中工作?
推荐答案
在回调函数内调用this会创建到this对象的新绑定,而不是正则函数表达式中的vue对象。
您可以使用箭头语法定义函数,因此this不会被覆盖。
.catch((error) => {
if(error.response.status === 422){
this.$router.push({name: "Settings"});
}
})
More information
另一个选项
在axios调用之前定义this的另一个实例,并在收到响应后使用它。
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"});
}
});
},
这篇关于TypeError:无法读取未定义(读取';$ROUTER';)vuejs的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:TypeError:无法读取未定义(读取';$ROUTER';)vuejs的属性
基础教程推荐
猜你喜欢
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 从快速中间件中排除路由 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
