路由组件传参
路由組件傳參
在組件中使用?$route?會使之與其對應路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
使用?props?將組件和路由解耦:
取代與?$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 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?是靜態的時候有用。
const router = new VueRouter({routes: [{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }] })#函數模式
你可以創建一個函數返回?props。這樣你便可以將參數轉換成另一種類型,將靜態值與基于路由的值結合等等。
const router = new VueRouter({routes: [{ path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }] })URL?/search?q=vue?會將?{query: 'vue'}?作為屬性傳遞給?SearchUser?組件。
請盡可能保持?props?函數為無狀態的,因為它只會在路由發生變化時起作用。如果你需要狀態來定義?props,請使用包裝組件,這樣 Vue 才可以對狀態變化做出反應。
更多高級用法,請查看例子。
總結
- 上一篇: vue-router参数传递
- 下一篇: GraphQL 入门第一篇