Skip to content

Commit 6b42c4e

Browse files
zkerhcyposva
authored andcommitted
Create passing-props.md (#1559)
1 parent 5c2a291 commit 6b42c4e

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# 路由组件传参
2+
3+
在组件中使用`$route`会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的url上使用,限制了其灵活性。
4+
5+
使用props将组件和路由解耦:
6+
7+
**❌ 与$route耦合**
8+
9+
``` js
10+
const User = {
11+
template: '<div>User {{ $route.params.id }}</div>'
12+
}
13+
const router = new VueRouter({
14+
routes: [
15+
{ path: '/user/:id', component: User }
16+
]
17+
})
18+
```
19+
20+
**👍 使用props解耦**
21+
22+
``` js
23+
const User = {
24+
props: ['id'],
25+
template: '<div>User {{ id }}</div>'
26+
}
27+
const router = new VueRouter({
28+
routes: [
29+
{ path: '/user/:id', component: User, props: true }
30+
31+
// 对于包含命名视图的路由,你必须分别为每个命名视图添加props选项:
32+
{
33+
path: '/user/:id',
34+
components: { default: User, sidebar: Sidebar },
35+
props: { default: true, sidebar: false }
36+
}
37+
]
38+
})
39+
```
40+
41+
这样你便可以在任何地方使用该组件,使得该组件更易于重用和测试。
42+
43+
### 布尔模式
44+
45+
如果props被设置为true,`route.params`将会被设置为组件属性。
46+
47+
### 对象模式
48+
49+
如果props是一个对象,它会被按原样设置为组件属性。当props是静态的时候有用。
50+
51+
``` js
52+
const router = new VueRouter({
53+
routes: [
54+
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
55+
]
56+
})
57+
```
58+
59+
### 函数模式
60+
61+
你可以创建一个函数返回props。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等。
62+
63+
``` js
64+
const router = new VueRouter({
65+
routes: [
66+
{ path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
67+
]
68+
})
69+
```
70+
71+
Url: `/search?q=vue` 会将 `{query: "vue"}` 作为属性传递给SearchUser组件。
72+
73+
请尽可能保持props函数为无状态的,因为它只会在路由发生变化时起作用。如果你需要状态来定义props,请使用包装组件,这样vue才可以对状态变化做出反应。
74+
75+
76+
更多高级用法,请查看[例子](https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js).

0 commit comments

Comments
 (0)