Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,便于构建单页面应用。
Vue Router 路由组件的传参主要有三种方式
布尔模式中,在router中将props属性设置为true,就可以在匹配的组件里通过props数组获取参数。
props让组件与路由解耦,使得组件更易于重用和测试
//布尔模式路由传参
{
path: "/profile/:mine",
component: profile,
props: true
}
如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。
{
path: ‘/position/:id/city/:city‘,
component: position,
props: { age: 20 }
},
router中,如果props设为一个函数,那么组件中可以在props数组中将其该函数的返回对象,从而获取参数
{
path: ‘/search‘,
component: search,
props: function (route) {
return { query: route.query.keyword };
}
},
<body>
<div id="app">
<ul>
<router-link tag="li" to="/" exact active-class="active">首页</router-link>
<router-link tag="li" to="/position/35/city/北京" exact active-class="active">职位</router-link>
<router-link tag="li" to="/search?keyword=前端" exact active-class="active">搜索</router-link>
<router-link tag="li" to="/profile/我的" exact active-class="active">我的</router-link>
</ul>
<router-view></router-view>
</div>
<script>
const position = {
props: [‘age‘],
template: `<div>{{age}}---{{$route.params.id}}---{{$route.params.city}}</div>`
}
const search = {
props: [‘query‘],
template: `<div>search-{{query}}</div>`
}
const profile = {
props: [‘mine‘],
template: `<div>profile-{{mine}}</div>`
}
var router = new VueRouter({
mode: ‘hash‘,//默认是hash
//将url和组件匹配
routes: [
//布尔模式路由传参
{
path: "/profile/:mine",
component: profile,
props: true
},
//对象模式路由传参
{
path: ‘/position/:id/city/:city‘,
component: position,
props: { age: 20 }
},
//函数模式路由传参
{
path: ‘/search‘,
component: search,
props: function (route) {
return { query: route.query.keyword };
}
},
{
path: "*",
component: {
template: `
<h1>404 page not found</h1>
`
}
}
]
});
var vm = new Vue({
el: "#app",
router
});
</script>
</body>
参数的存放并不以传参模式为区分,而是根据url来判定
类似post/:id的url参数存放在$route.params中
而post?id=1的url参数存放在$route.query中
为了测试,在案例代码的基础上做些增改
DOM:
<router-link tag="li" to="/search/前端" exact active-class="active">搜索1</router-link>
<router-link tag="li" to="/search?keyword=前端" exact active-class="active">搜索2</router-link>
router:
//函数模式
{
path: ‘/search/:pos‘,
component: search,
props: function (route) {
return { query: route.params.pos };
}
},
//函数模式
{
path: ‘/search‘,
component: search,
props: function (route) {
return { query: route.query.keyword };
}
}
函数模式传参,搜索1的参数在params中,而搜索2的参数在query中。
原文:https://www.cnblogs.com/ltfxy/p/12650520.html