两种方式:1.使用 $route 2.使用 props
优缺点:
1.使用 $route 会使之与其对应路由形成高度耦合
2.使用 props 将组件和路由解耦
$route,在to属性里传参
$route.params || $ route.query
html:
<router-link :to= "{ name:'haha', params:{id:'7',id2:'0'}}">/a</router-link>
<router-link :to= "{path:'/nav',query:{name:'b',id:'1'}}">/b</router-link>
router/index.js
{ path: '/a/',name:'a', component: HelloWorld},
{ path: '/b', component: HelloWorld},
{ path: '/haha/:id',name:'haha', component: hello},
{ path: '/nav', component: navbar},
params传参和query传参有什么区别:
-
用法上的
刚query要用path来引入,params要用name来引入,接收参数都是类似的,分别是this. r o u t e . q u e r y . n a m e 和 t h i s . route.query.name和this. route.query.name和this.route.params.name。 -
展示上的
query类似get传参,params则类似于post,前者在浏览器地址栏中显示参数,后者则不显示query: http://localhost:8080/#/nav?name=b&id=1 params: http://localhost:8080/#/haha/7
-
params是路由的一部分(动态路由),必须要有。query是拼接在url后面的参数,没有也没关系。
params一旦设置在路由,params就是路由的一部分,如果这个路由有params传参,但是在跳转的时候没有传这个参数,会导致跳转失败或者页面会没有内容。
比如:
a跳转到haha,haha是动态路由,跳转时必须传入id;<router-link :to= "{ name:'haha', params:{id:'7',id2:'0'}}">/a</router-link> { path: '/a',name:'a', component: HelloWorld}, { path: '/haha/:id',name:'haha', component: hello},
-
params、query不设置也可以传参,params不设置的时候,刷新页面或者返回参数会丢失;
例子:
html:
<router-link :to= "{ name:'haha', params:{id:'7',id2:'0'}}">/a</router-link>
<router-link :to= "{path:'/nav',query:{name:'b',id:'1'}}">/b</router-link>
router/index.js
{ path: '/a/',name:'a', component: HelloWorld},
{ path: '/b', component: HelloWorld},
{ path: '/haha/:id',name:'haha', component: hello},
{ path: '/nav', component: navbar},
a跳转到haha,收到参数id和id2,但是刷新页面,除了haha需要的动态路由id参数外,其他参数都丢失;
b跳转到nav,收到参数name和id,刷新页面,依旧可以拿到name和id;
总结:
name¶ms:在地址栏不显示参数,刷新页面参数丢失,必须是匹配动态路由的字段;
path&query:在地址栏显示参数,刷新页面参数仍然在,参数没有限制;
props,在每条路由里传参,在组件中用props接收;
props在路由中可以以三种模式传入:布尔、对象、函数;
router/index:
function dynamicPropsFn (route) {
const now = new Date()
return {
name: (now.getFullYear() + parseInt(route.params.years)) + '!'
}
}
let router = new Router({
routes: [
{ path: '/', component: HelloWorld }, // No props, no nothing
{ path: '/hello/:name', component: HelloWorld, props: true }, // Pass route.params to props
{ path: '/static', component: HelloWorld, props: { name: 'world' }}, // static values
{ path: '/dynamic/:years', component: HelloWorld, props: dynamicPropsFn }, // custom logic for mapping between route and props
]
})
html:
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/hello/you">/hello/you</router-link></li>
<li><router-link to="/static">/static</router-link></li>
<li><router-link to="/dynamic/1">/dynamic/1</router-link></li>
</ul>
<router-view class="view" foo="123"></router-view>
子组件:
<template>
<div class="hello">
<h1>{{ name }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props:['name'],
}
</script>
//you
//word
//2019!
布尔值:如果 props 被设置为 true,route.params 将会被设置为组件属性。在组件中通过props接收参数;
对象:如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。
函数:创建一个函数返回props,可以将参数转换成另一种类型,将静态值与基于路由的值结合等等。