将路由推送到函数内的父组件(Vue)
Push route to parent component inside a function (Vue)
我觉得我遗漏了一些非常明显的东西,但我想不通。请帮忙!
我定义了以下路线:
const routes = [
{
path: '/',
name: 'Login',
component: () => import('../views/Login.vue'),
meta: {
authRedirect: true
}
},
{
path: '/companies',
name: 'Companies',
component: () => import('../views/Companies.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/companies/:id',
name: 'Company',
component: () => import('../views/Company.vue'),
meta: {
requiresAuth: true
}
},
{
path: '*',
name: '404',
component: () => import('../views/404.vue')
}
]
然后我的组件中有以下内容:
export default {
name: 'Company',
data() {
return {
company: {}
}
},
methods: {
getCompanyDetails: function() {
let self = this
axios.get('/api/companies/' + this.$route.params.id).then(function(response) {
self.company = response.data
}).catch(function() {
self.$router.push('companies')
})
}
},
created() {
this.getCompanyDetails()
}
}
如果 API returns 数据,基本上一切正常,但在 catch
函数中,我试图将路由推回到 /companies。但它正在重定向到 /companies/companies。如何将其重定向到正确的路线?
您是否尝试过 $router.push('/companies')
(路径中带有 /)?
此外,如果你想让它更清楚,你可以使用$router.push({ name: 'Companies' })
,它会匹配你的路由中定义的name
。
我觉得我遗漏了一些非常明显的东西,但我想不通。请帮忙! 我定义了以下路线:
const routes = [
{
path: '/',
name: 'Login',
component: () => import('../views/Login.vue'),
meta: {
authRedirect: true
}
},
{
path: '/companies',
name: 'Companies',
component: () => import('../views/Companies.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/companies/:id',
name: 'Company',
component: () => import('../views/Company.vue'),
meta: {
requiresAuth: true
}
},
{
path: '*',
name: '404',
component: () => import('../views/404.vue')
}
]
然后我的组件中有以下内容:
export default {
name: 'Company',
data() {
return {
company: {}
}
},
methods: {
getCompanyDetails: function() {
let self = this
axios.get('/api/companies/' + this.$route.params.id).then(function(response) {
self.company = response.data
}).catch(function() {
self.$router.push('companies')
})
}
},
created() {
this.getCompanyDetails()
}
}
如果 API returns 数据,基本上一切正常,但在 catch
函数中,我试图将路由推回到 /companies。但它正在重定向到 /companies/companies。如何将其重定向到正确的路线?
您是否尝试过 $router.push('/companies')
(路径中带有 /)?
此外,如果你想让它更清楚,你可以使用$router.push({ name: 'Companies' })
,它会匹配你的路由中定义的name
。