這裏寫自定義目錄標題
vue-router路由組件傳參解耦
路由組件中使用$route取路由參數會導致該路由與該組件形成高度綁定耦合
原始取參方式
// 路由組件
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
//路由定義
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
props解耦
// 路由組件
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const Sidebar = {
props: ['id'],
template: '<div>Sidebar {{ id }}</div>'
}
//路由定義
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 對於包含命名視圖的路由,你必須分別爲每個命名視圖添加 props 選項:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
布爾模式
如果 props 被設置爲 true,route.params 將會被被定義在組件的props中
對象模式
如果 props 是一個對象,它會被按原樣設置爲組件屬性。當 props 是靜態的時候有用。
// 路由組件
const Promotion= {
props: ['info'],
template: '<div>Sidebar {{ info}}</div>' // 結果 111
}
//路由定義
const router = new VueRouter({
routes: [
{ path: '/promotion/from-newsletter', component: Promotion, props: { info: 111} }
]
})
函數模式
你可以創建一個函數返回 props。這樣你便可以將參數轉換成另一種類型,將靜態值與基於路由的值結合等等
// 輸入的導航路由/search/1900
// 路由組件
const SearchUser= {
props: ['name'],
template: '<div>SearchUser{{ name}}</div>' // 結果 2019--1900!
}
//路由定義
const router = new VueRouter({
routes: [
{ path: '/search/:years', component: SearchUser, props: dynamicPropsFn }
]
})
function dynamicPropsFn (route) {
const now = new Date()
return {
name: `${now.getFullYear()}--${parseInt(route.params.years)}!`
}
}