最近,由于工作需要,需要去面试一些前端,由于自己是那种实操型的程序猿,不擅长这方面,但是没办法,只能硬着头皮上,第一次有些紧张,后来慢慢就好了,在过程中,发现面试别人自己可以系统的学到很多知识,比如说有些原理性的东西,系统的知识,就可以在学习一遍,并且比之前理解的更透彻了,所以说,什么时候都可以学习,加油吧,骚年。
下面主要说一下vue $router 路由传参的3种方法详解,里边包括了一些,配置,传参,接参的方法,来吧,上代码
第一种:使用router的name属性也就是params来传递参数
这个方法有一个bug就是当你传参过去的时候,再次刷新页面时参数就会丢失。解决方法下边会说到。
step:1,首先需要在router/index.js里边配置每个页面的路径,name属性,看例子:
import Vue from 'vue' import Router from 'vue-router' const _import = require('./_import_' + process.env.NODE_ENV) 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 })
step:2,在传值页面的写法:
//用这种方法传参,必须这么些,不能写path,否则你在取参数的时候this.$router.params.userId就是undefined.这是因为,params只能用name来引入路由, this.$router.push({ name:"'Message'",//这个name就是你刚刚配置在router里边的name params:{ userId:"10011" } })
step:3,在取值页面的写法:
切记,再取参数的时候一定是this.
router,切记。
this.$route.params.userId
第二种:使用query来传递参数
step:1,在传值页面的写法:
this.$router.push({ path:"/login",//这个path就是你在router/index.js里边配置的路径 query:{ userId:"10011" } })
step:2,在取值页面的写法:
第一种:
this.$router.currentRoute.query.userId 第二种: 这种方法再取参数的时候一定是this.$route 不是 this.$router,切记。 this.$route.query.userId
第三种:使用vue里的<router-link>标签来传递参数
step:1,在传值页面的写法:
<router-link target="_blank" :to="{path:'/login',query:{userId: "33333"}}"> </router-link>
step: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
总结
真的是学无止境,好多时候还是要注意好多细节的东西,否则学到的就只是皮毛。以上为我项目过程中遇到的坑以及总结的经验,若有什么错误的地方,还请伙伴们多多指正。
作者:愿醒静卧忘尘谷
链接:https://www.jianshu.com/p/ed6f2d4b2d0e
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。