vue路由传参的方法
最近小编在公司也是在做vue项目,所以在有些功能需求上需要vue路由传参,所以写了这边博文,对于vue路由传参的方法做了小总结。
第一种:使用router的name属性也就是params来传递参数
这个方法有一个bug就是当你传参过去的时候,再次刷新页面时参数就会丢失。解决方法下边会说到。
1:首先需要在router/index.js里边配置每个页面的路径,name属性,看例子:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export const constantRouterMap = [{
path: '/login/:userId/:id',
name:'Message', //就是要在路由配置里边配置这个属性,用来知道你要跳转到那个页面的名字
/***
* 如果想做到页面刷新,参数不丢失,就必须在path后面加上这个参数
* 但是这样做的话就会导致参数显示在url的后面,(在这一点上)跟query没什么区别了。
* 多个参数也可以一直往后边追加
*/
component: _import('login/index'),
hidden: true
},
{
path: '',
component: Layout,
redirect: 'dashboard',
icon: 'dashboard',
hidden: true,
noDropDown: true,
children: [{
path: 'dashboard',
name: '首页',
component: _import('main/index'),
meta: {
title: 'dashboard',
icon: 'dashboard',
noCache: true
}
}]
}
]
export default new Router({
routes: constantRouterMap
})
2:在传值页面的写法:
//用这种方法传参,必须这么些,不能写path,否则你在取参数的时候this.$router.params.userId就是undefined.这是因为,params只能用name来引入路由,
this.$router.push({
name:"'Message'",//这个name就是你刚刚配置在router里边的name
params:{
userId:"10011"
}
})
step:3,在取值页面的写法:
this.$route.params.userId
第二种:使用query来传递参数
1:在传值页面的写法:
this.$router.push({
path:"/login",//这个path就是你在router/index.js里边配置的路径
query:{
userId:"10011"
}
})
2:在传值页面的写法:
第一种:
this.$router.currentRoute.query.userId
第二种:
this.$route.query.userId
三:使用vue里的标签来传递参数
1:在传值页面的写法:
<router-link target="_blank"
:to="{path:'/login',query:{userId: "33333"}}">
</router-link>
2:在取值页面的写法:同第二种。
其实,router-link也可以使用name的方法传参
同样,这种方法也需要在router/index.js里边配置每个页面的路径,name属性
name:'Message', //就是要在路由配置里边配置这个属性,用来知道你要跳转到那个页面的名字
<router-link :to="{name:''Message'',params:{userId:'1234'}}">Hi页面1</router-link>
取参方法:
this.$route.params.userId