VueJS路由跳转异常:点击BlogItem无法加载BlogToRead组件
问题解决思路
1. 修复"Illegal argument undefined"错误
控制台能打印参数但报错,大概率是$router.push写法或路由配置存在格式问题:
- 检查路由配置中
/blog/{id}/{title}的参数声明,必须用:xxx格式定义:// main.js路由配置示例 const routes = [ // ...其他路由 { path: '/blog/:id/:title', name: 'BlogToRead', component: () => import('./components/BlogToRead.vue') } ] - 调整
BlogItem的跳转逻辑,推荐使用路由name+params的方式传递参数,避免路径拼接错误:// BlogItem.vue跳转代码 this.$router.push({ name: 'BlogToRead', params: { id: this.postId, title: this.title } }) - Vue Router的
push方法返回Promise,未捕获错误会抛出异常,可添加catch处理合法的导航取消错误:this.$router.push(/* 跳转配置 */).catch(err => { if (err.name !== 'NavigationDuplicated') console.error(err) })
2. 实现仅加载BlogToRead组件
问题出在App.vue的结构设计上,当前应该是把BlogItem列表和路由出口<router-view>放在了同一层级,导致所有路由都会渲染列表。调整方式如下:
- 修改
App.vue,仅保留路由出口:<!-- App.vue --> <template> <div id="app"> <router-view></router-view> </div> </template> - 新增Home组件承载BlogItem列表,并配置首页路由:
这样访问// main.js路由配置 const routes = [ { path: '/', name: 'Home', component: () => import('./components/Home.vue') // Home组件内渲染BlogItem列表 }, { path: '/blog/:id/:title', name: 'BlogToRead', component: () => import('./components/BlogToRead.vue') } ]/时加载Home组件(含BlogItem列表),访问/blog/{id}/{title}时仅加载BlogToRead组件。
内容的提问来源于stack exchange,提问作者Eternan0
相关产品推荐
相关产品推荐

