[英]vue-router default child route for tabs
我正在嘗試使用包含 2 個列表的選項卡的主頁,默認情況下打開 1 個。
我有以下路線配置,我已更改名稱以簡化
let routes = [{
path: '/',
name: 'home',
component: require('./views/Home.vue'),
children: [{
path: 'list1',
name: 'home.list1',
component: require('./views/List1.vue')
}, {
path: 'list2',
name: 'home.list2',
component: require('./views/List2.vue')
}]
}
在./views/Home.vue
,每個選項卡(子路由)在 2 個<router-link>
下方都有一個<router-view></router-view>
。
當我訪問應用程序路由http://domain/
我想激活list1
選項卡。 我目前可以做到這一點的唯一方法是訪問http://domain/list1
。
我試過了
children: [{
path: '',
name: 'home.list1'
這最初效果很好,但是如果我訪問http://domain/list2
,我的兩個選項卡鏈接(路由器鏈接)都處於活動狀態。
我無法運行但有助於上下文的JSFiddle
有沒有更好的解決方案?
使用重定向再添加一個子路由(應該是第一個)
children: [{
path: '',
redirect: 'list1', // default child path
},
...
]
為了使組件(選項卡)在訪問父路由時顯示為默認值,您需要添加一個路徑為 '' (空字符串)
以下是 Vue Router 文檔中的示例
const router = new VueRouter({
routes: [
{
path: '/user/:id', component: User,
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: UserHome },
// ...other sub routes
]
}
]
})
不要使用“/”,它將被視為根路由。
我需要將重定向放在父級上,並且它在第一次加載時起作用。 否則它只有在我重新加載頁面時才有效。
希望它有效。
let routes = [{
path: '/',
name: 'home',
redirect: 'home.list1',
component: require('./views/Home.vue'),
children: [{
path: '',
name: 'home.list1',
component: require('./views/List1.vue')
}, {
path: 'list2',
name: 'home.list2',
component: require('./views/List2.vue')
}]
}
如果您的回家路線不是“/”,我認為您想做的事情有效
routes: [
{ path: '/home',
name: 'home',
component: require('./views/home.vue')
children: [
{ path: '/', name: 'list1', component: list1 },
{ path: 'list2', name: 'list2', component: list2},
],
}
]
這將在您的初始 . 然后你可以使用路由器鏈接到導航到列表2:
<router-link :to="{ name: 'list2', params: { ...}}">
或者,也許我不明白這個問題。
這是有效的。
您必須在父路由'home'
上使用redirect: {name: 'home.list1'}
(對於命名路由)屬性。
確保為命名路由(如上)或路徑使用正確的重定向屬性格式: redirect: '/list1'
。
這是正確的路由配置,它與您的配置只有 1 行( redirect
)不同:
let routes = [{
path: '/',
name: 'home',
redirect: 'home.list1',
component: require('./views/Home.vue'),
children: [{
path: 'list1',
name: 'home.list1',
component: require('./views/List1.vue')
}, {
path: 'list2',
name: 'home.list2',
component: require('./views/List2.vue')
}]
}
然后每次訪問/
(您的'home'
路線)都會被重定向到/list1
。
此外, router-link-active
和router-link-exact-active
將在子鏈路(兩者)和父鏈路(僅router-link-active
)上正確分配。
這也適用於更深層嵌套的非子路由和子路由。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.