• vue中this.$router.push()路由传值和获取的两种常见方法


    1、路由传值   this.$router.push()

    (1) 想要导航到不同的URL,使用router.push()方法,这个方法会向history栈添加一个新纪录,所以,当用户点击浏览器后退按钮时,会回到之前的URL

    (2)当点击 <router-link> 时,这个方法会在内部调用,即点击 <router-link :to="..."> 等同于调用 router.push(...)

      a)      声明式:<router-link :to="...">

      b)      编程式:router.push(...)

      c)      该方法的参数可以是一个字符串路径,或者一个描述地址的对象。  

    // 字符串
    router.push('home')
     
    // 对象
    this.$router.push({path: '/login?url=' + this.$route.path});
     
    // 命名的路由
    router.push({ name: 'user', params: { userId: 123 }})
     
    // 带查询参数,变成/backend/order?selected=2
    this.$router.push({path: '/backend/order', query: {selected: "2"}});
     
    // 设置查询参数
    this.$http.post('v1/user/select-stage', {stage: stage})
          .then(({data: {code, content}}) => {
                if (code === 0) {
                    // 对象
                    this.$router.push({path: '/home'});
                }else if(code === 10){
                    // 带查询参数,变成/login?stage=stage
                    this.$router.push({path: '/login', query:{stage: stage}});
               }
    });
     
    // 设计查询参数对象
    let queryData = {};
    if (this.$route.query.stage) {
        queryData.stage = this.$route.query.stage;
    }
    if (this.$route.query.url) {
        queryData.url = this.$route.query.url;
    }
    this.$router.push({path: '/my/profile', query: queryData});

    2、获取参数的两种常用方法:params和query

    (1)由于动态路由也是传递params的,所以在 this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面。

    及通过路由配置的name属性访问

    this.$router.push({name:"menuLink",params:{alert:"页面跳转成功"}})

    (2)在目标页面通过this.$route.params获取参数:

    <p>提示:{{this.$route.params.alert}}</p>

    (3)在目标页面通过this.$route.query 获取参数

    //传值
    this.$router.push({path:"/menLink",query:{alert:"页面跳转成功"}})
    
    //用query获取值
    <p>提示:{{this.$route.query.alert}}</p>

    两种方式的区别是query传参的参数会带在url后边展示在地址栏,params传参的参数不会展示到地址栏。需要注意的是接收参数的时候是route而不是router。两种方式一一对应,名字不能混用

  • 相关阅读:
    BPM已经全面开启
    终于理解集线器、交换机、路由器之间的区别了
    Linux系统桥接模式下配置静态ip地址
    理解并手写Spring MVC框架
    Java 8 Funciton、Consumer、Predicate的作用及用法
    你想了解的分布式文件系统HDFS,看这一篇就够了
    分布式处理框架Hadoop的安装与使用
    CentOS7 中常用命令
    VMware安装Centos7并联网使用
    理解Spring AOP的实现方式与思想
  • 原文地址:https://www.cnblogs.com/toonezhr/p/10325457.html
Copyright © 2020-2023  润新知