我们在使用vue做单页面应用难免会用到vue-router,那把项目中的经常用到方法整理一下,方便日后查找与回顾。
1.$route.params
一个 key/value 对象,如果没有路由参数,就是一个空对象。
格式:path: '/detail/:id' 动态路径参数 以冒号开头。
const routes = [
{path: '/detail/:id', component: Detail, name: 'detail', meta: {title: ''}},
];
一个参数时:
格式: /user/:username
$route.params:{ username: 'evan' }
多个参数时:
格式:/user/:username/post/:post_id
$route.params:{ username: 'evan', post_id: 123 }
复用组件时,可以使用watch监听$route 对象
watch: {
'$route' (to, from) {
// 对路由变化作出响应...
}
}
或者用这种方式,只要$route发生变化,就可以做某事:
watch: {
// 如果路由有变化,会再次执行该方法
' $route': 'doSomeThing'
},
methods: {
doSomeThing(){}
}
案例
// 当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在每个组件内使用。
// 可以通过this.$route.params.id来取上动态的id
<router-link :to="{path: '/detail/' + this.$route.params.id}" >
此团详情
</router-link>
// 还可以用命名路由的方式:
<router-link :to="{ name: 'detail', params:{ id: this.$route.params.id }}" >
此团详情
</router-link>
// 还可以用router.push()的方式
router.push({name:'detail', params: { id: this.$route.params.id}})
// 以上三种方式都可以实现跳转,都可以通过this.$route.params来取到参数
2.$route.query
对于路径 /foo?user=1,则有 $route.query.user == 1,如果没有查询参数,则是个空对象。
用法
<router-link :to="{ path: '/backend/verify_coupon', query:this.queryData }">验证抵扣券</router-link>
3定义路由的时候可以配置 meta 字段
案例:
// 定义路由的时候在meta中加入自定义字段
const routes = [
{path: '/activity', component: Activity, name: 'activity', meta: {isNeedAuth: false, title: '活动现场'}},
{path: '/start', component: Start, name: 'start', meta: {isNeedAuth: false, title: '活动现场'}},
];
const router = new VueRouter({...});
router.beforeEach((to, from, next) => {
// 动态修改页面的title
setTitleHack(to.meta.title);
// 根据自定义的路由元信息来做判断:
if (to.meta.isNeedAuth !== false) {
// do something
} else {
// do something
}
next();
});
综合案例
// 命名路由,append 属性,查询参数,router-link渲染成<li>标签
<router-link tag="li" :to="{name:'demandindex', append:true, query: {isFormBackend: 1}, activeClass: 'bottom-nav-active'}">
</router-link>
// to的值:字符串形式
<router-link to="banner.image_url" ></router-link>
// to的值:对象形式,拼接多个动态参数
<router-link :to="{path: '/my/modify?modify=fullname&val=' + profile.nickname}" ></router-link>
// to的值:对象形式
<router-link :to="{path: '/home'}">返回首页</router-link>
// to的值:对象形式,拼接动态参数
<router-link to="{path: '/backend/coupon_order_detail/' + product.order_id+'?order_status='+product.order_status}"></router-link>
// to的值:对象形式,带一个路径参数
<router-link :to="{path: '/detail/' + this.$route.params.id}" ></router-link>