在使用通过路由使用组件时,我们会出现传参的情况,一般可以通过$route.params 或渠道params 中的参数。然而将会增加组件之前耦合度,违反了我们的编程原则。在开发过程是我们要最大限度的实现解耦,提高组件复用性。
使用props将组件和路由解耦。
例如,在解耦之前我们是这样实现路由传参的
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
实例中,我们的User 组件只能在路由的情况下使用,否则我们将获取不到route.params.id。这就是User组件与路由的耦合性过高降低了User 组件的 复用性
现在我们将用prop与之解耦
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 }
}
]
})
User 定义了 props ,在路由规则中 我们设置props:true。
这样我们的User 组件不仅在该路由中可以使用,也可以单独使用。例如父子组件中,给props 中id 传入具体值。还User组件以最大的自由。
在路由使用props 传参时,我们的具体方法就是 将props 设为 true,这种模式我们称之为“布尔模式”,在这两种模式之后我们还有 对象模式和函数模式
对象模式
定义路由规则时,props的值为一个对象,这个对象将会被原样的变为组件属性,组件可以通过props 接收
const router = new VueRouter({
routes: [
{ path: '/User', component: User, props: { id: 5 } }
]
})
函数模式
我们也可以 使用函数返回对象的方式传参,这样的好处我可以给函数添加参数,更加灵活
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: (route) => ({ id: route.params.id }) }
]
})
如果我们使用对象模式,我们不方便将id 作为参数传递过去,函数可以轻松的实现。
//一下是不推荐的传参方式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>路由传参</title>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
</head>
<body>
<div id="test">
<router-link to="/com_a?name=xiaoming&passward=333">组件1</router-link>
<router-link to="/com_b/leili/567">组件2</router-link>
<router-view></router-view>
</div>
<template id="c_1">
<div>
<p>这是组件1</p>
<p>{{$route.query}}</p>
</div>
</template>
<template id="c_2">
<div>
<p>这是组件2</p>
<p>{{$route.params.username}}</p>
</div>
</template>
<script>
var com_1={
template:'#c_1'
}
var com_2={
template:'#c_2'
}
var routes=[
{
path:'/com_a',
component:com_1
},
{
path:'/com_b/:username/:password',
component:com_2
}
]
const router = new VueRouter({
routes
})
new Vue({
el:"#test",
router
})
</script>
</body>
</html>