第一种:使用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.route 不是 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里的标签来传递参数
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

作者:haoyanfeng
链接:https://www.jianshu.com/p/ed6f2d4b2d0e
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐