为啥 Vue Router (0.7.13) 不匹配子路由?
Posted
技术标签:
【中文标题】为啥 Vue Router (0.7.13) 不匹配子路由?【英文标题】:Why Vue Router (0.7.13) does not match sub routes?为什么 Vue Router (0.7.13) 不匹配子路由? 【发布时间】:2017-02-08 21:29:24 【问题描述】:如果我这样做:
'/sales':
component: NotFound,
subRoutes:
'/':
component: NotFound
,
'/report':
name: 'sales.report',
component: SalesReport
,
'/create':
name: 'sales.create',
component: SalesCreate
,
'/edit/:i':
name: 'sales.edit',
component: SalesEdit
,
'/list':
name: 'sales.list',
component: SalesList
无论sales
URL 是什么,Vue 总是会转到组件NotFound
(我猜它匹配父级)。
但如果我这样写:
'sales/report':
name: 'sales.report',
component: SalesReport
,
'sales/create:
name: 'sales.create',
component: SalesCreate
它按预期工作。我的问题:为什么我不能使用 subRoutes? (使用 Vue 1.0.26)
【问题讨论】:
据我所知,根组件将始终使用其嵌套路由呈现。解决方法是让你的根组件为空,除了你的<router-view>
。
【参考方案1】:
按名称调用嵌套路由应该没有问题。
https://jsfiddle.net/662u1pah/4/
// index.html
<div id="app">
<h1>My App</h1>
<ul>
<li><a v-link=" name: 'sales' ">Go to /sales</a></li>
<li><a v-link=" name: 'sales.report' ">Go to /sales/report</a></li>
<li><a v-link=" name: 'sales.create' ">Go to /sales/create</a></li>
<li><a v-link=" name: 'sales.edit', params: i: 2 ">Go to /sales/edit/2</a></li>
<li><a v-link=" name: 'sales.list' ">Go to /sales/list</a></li>
</ul>
<router-view></router-view>
</div>
// index.js
var Root = Vue.extend(
template:
'<div class="root">' +
'<h2>This is Root. I always show</h2>' +
'<router-view></router-view>' +
'</div>'
)
var SalesReport = Vue.extend(
template: '<p>This is Sales Report</p>'
)
var SalesCreate = Vue.extend(
template: '<p>This is Sales Create</p>'
)
var SalesEdit = Vue.extend(
template: '<p>This is Sales Edit ( $route.params.i )</p>'
)
var SalesList = Vue.extend(
template: '<p>This is Sales List</p>'
)
// configure router
var router = new VueRouter()
router.map(
'/':
component: Root,
,
'/sales':
name: 'sales',
component: Root,
subRoutes:
'/report':
name: 'sales.report',
component: SalesReport
,
'/create':
name: 'sales.create',
component: SalesCreate
,
'/edit/:i':
name: 'sales.edit',
component: SalesEdit
,
'/list':
name: 'sales.list',
component: SalesList
)
// start app
var App = Vue.extend()
router.start(App, '#app')
【讨论】:
现在我知道为什么了,我的“根”没有以上是关于为啥 Vue Router (0.7.13) 不匹配子路由?的主要内容,如果未能解决你的问题,请参考以下文章
为啥vue中子路由点击router-link只能刷新一次子页面?
为啥通过 Vue-router 传递数据返回“[object Object]”?
为啥 router.push 不起作用? [Vue 3] [Vuex 4]