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的属性


猜你喜欢
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01