vue-router 3.x 中路由传参

vue-router路由属性配置说明

export default new Router({
    mode: 'history', //路由模式,取值为history与hash
    base: '/', //打包路径,默认为/,可以修改
    routes: [
    {
        path: string, //路径
        ccomponent: Component; //页面组件
        name: string; // 命名路由-路由名称
        components: { [name: string]: Component }; // 命名视图组件
        redirect: string | Location | Function; // 重定向
        props: boolean | string | Function; // 路由组件传递参数
        alias: string | Array<string>; // 路由别名
        children: Array<RouteConfig>; // 嵌套子路由
        beforeEnter?: (to: Route, from: Route, next: Function) => void; // 路由单独钩子
        meta: any; // 自定义标签属性,比如:是否需要登录
        icon: any; // 图标
        // 2.6.0+
        caseSensitive: boolean; // 匹配规则是否大小写敏感?(默认值:false)
        pathToRegexpOptions: Object; // 编译正则的选项
    }
    ]
})

一、使用router-link进行路由导航,传递参数

=> 父组件中:使用<router-link to="/需要跳转的路由路径/需要传递的参数"></router-link>标签进行导航

vue-router 3.x 中路由传参

show是页面路由路径,111是需要传递的参数

=>子组件中:使用this.$route.params来接收路由参数,这时params是个json的形式,你可以选择你想要的参数。

vue-router 3.x 中路由传参

=>路由配置文件中:

vue-router 3.x 中路由传参

:id用来为参数占位

=>地址栏中:

vue-router 3.x 中路由传参

在地址栏中显示传递的参数id,即111, ,刷新页面,参数不丢失

二、直接调用$router.push 实现携带参数的跳转

=> 父组件中:

vue-router 3.x 中路由传参

模板渲染中调用函数,传递参数

=> 子组件中:

vue-router 3.x 中路由传参

仍然使用 this.$route.params 获取参数

=> 路由配置文件中:

vue-router 3.x 中路由传参

:id用来为参数占位

=> 地址栏中:

vue-router 3.x 中路由传参

在地址栏中显示传递的参数id, ,刷新页面,参数不丢失

三、通过路由属性中的name来确定匹配的路由,通过params来传递参数

=> 父组件中:

vue-router 3.x 中路由传参
使用name来匹配路由

=> 子组件中:

vue-router 3.x 中路由传参

依然使用 this.$route.params 接收参数

=> 路由配置中:

vue-router 3.x 中路由传参
设置name匹配,但是path不需要变量占位

=> 地址栏中:
vue-router 3.x 中路由传参
地址栏中不显示参数,刷新页面,参数丢失

四、使用path来匹配路由,然后通过query来传递参数,这种情况下 query传递的参数会显示在url后面?id=?

=> 父组件中:

vue-router 3.x 中路由传参
注意这里使用query来传递参数!!与上面是不一样的。

=> 子组件中:

vue-router 3.x 中路由传参
使用 this.$route.query来接收参数,也是个json格式

=> 路由配置文件中:

vue-router 3.x 中路由传参

=> 地址栏中:

vue-router 3.x 中路由传参
参数显示在地址栏中,刷新页面参数不丢失

****这里要特别注意 :在子组件中 获取参数的时候是(route.params 而不是)router ,这很重要~~~
总结:

  1. this.$router.push进行编程式路由跳转
  2. router-link 进行页面按钮式路由跳转
  3. this.$route.params获取路由传递参数
  4. this.$route.query获取路由传递参数
  5. paramsquery都是传递参数的,params不会在?后面出现,并且params参数是路由的一部分,使用params传参的时候在路由配置文件中的ptah里面一定存在形如:id变量占位的,相当于post请求。 query则是我们通常看到的url后面的跟在后面的显示参数,使用query传参的时候在路由配置文件中的ptah里面一定不要存在形如:id变量占位的,相当于get请求