在组件中使用$route会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的URL上使用,限制了其灵活性
也就是说含有{{$route.params.id}}的组件在其他地方根本不能用,因为有些地方根本不需要{{$route.params.id}}这个内容
使用props将组件和路由解耦
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 }
}
]
})
这样你便可以在任何地方使用该组件,使得该组件更易于重用和测试。
完整例子:
<body class="">
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
<div id="app">
<h1>路由传参</h1>
<router-link to="/user/111">a title</router-link>
<br />
<router-link to="/user/222">b title</router-link>
<router-view name="a"></router-view>
<router-view></router-view>
</div>
<script>
var user1 = {
props: ['id'],
template: "<div>this is {{id}} </div>"
};
var user2 = {
props: ['id'],
template: "<div>that is {{id}} </div>"
};
const router = new VueRouter({
routes: [{
path: "/user/:id",
components:{a:user1,default:user2},
props: {a:true,default:false}
}]
})
const app = new Vue({ router }).$mount("#app")
</script>
</body>
a title
b title点击a title 显示
this is 111
that is
点击b title
显示this is 222
that is
布尔模式:如果props被设置为true,route.params 将会被设置为组件属性
对象模式:如果props是一个对象,它会被按原样设置为组件属性。当props是静态的时候有用。
<body class="">
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
<div id="app">
<h1>Redirect</h1>
<router-link to="/user">a title</router-link>
<router-view></router-view>
</div>
<script>
var user = {
props: ['name'],
template: "<div>this is {{name}} </div>"
};
const router = new VueRouter({
routes: [{
path: "/user",
component: user,
props: {name:"lily"}
}]
})
const app = new Vue({ router }).$mount("#app")
</script>
</body>
点击显示this is lily
函数模式:你可以创建一个函数返回 props
。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等。
<body class="">
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
<div id="app">
<h1>Route props</h1>
<ul>
<li>
<router-link to="/dynamic/1">/dynamic/1</router-link>
</li>
</ul>
<router-view class="view" foo="123"></router-view>
</div>
<script>
function dynamicPropsFn(route) {
const now = new Date()
return {
name: (now.getFullYear() + parseInt(route.params.years)) + '!'
}
}
var Hello = {
props: ['name'],
template: '<h2 class="hello">Hello {{ name}}</h2>'
};
const router = new VueRouter({
routes: [
{ path: '/dynamic/:years', component: Hello, props: dynamicPropsFn }
]
})
const app = new Vue({ router }).$mount("#app")
</script>
</body>