Vue路由跳转方式的区别是什么

2023-06-26 路由 区别 跳转

今天小编给大家分享一下Vue路由跳转方式的区别是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

    在浏览器中,点击链接实现导航的方式,叫做声明式导航。例如:普通网页中点击 a标签链接。vue项目中点击router-link标签链接都属于声明式导航。
    在浏览器中,调用API方法实现导航的方式,叫做编程式导航。例如:普通网页中调用location.href跳转到新页面的方式,属于编程式导航。vue项目中编程式导航有this.$router.push(),this.$router.replace(),this.$router.go()。

    声明式导航router-link

    1. 不带参数

    <router-link :to="{name:'home'}"> 
    <router-link :to="{path:'/home'}"> 
    // name,path都行, 建议用name  
    // 注意:router-link中链接如果是'/'开始就是从根路由开始,如果开始不带'/',则从当前路由开始。

    2.带参数

    <router-link :to="{name:'home', params: {id:1}}">  
     
    // params传参数 (类似post)
    // 路由配置 path: "/home/:id" 或者 path: "/home:id" 
    // 不配置path ,第一次可请求,刷新页面id会消失
    // 配置path,刷新页面id会保留
     
    // html 取参  $route.params.id
    // script 取参  this.$route.params.id
     
     
    <router-link :to="{name:'home', query: {id:1}}"> 
     
    // query传参数 (类似get,url后面会显示参数)
    // 路由可不配置
     
    // html 取参  $route.query.id
    // script 取参  this.$route.query.id

    编程式导航

    1、this.$router.push

    跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面

    在这里插入代码片// 字符串
    this.$router.push('index') 
    
    // 对象
    this.$router.push({path: 'login-pw'})
    
    // 带参数
    this.$router.push({path: 'login-pw', query: {'account': this.account.account}})
    
    // 跳转后的页面获取参数
    this.account.account = this.$route.query.account

    2、this.$router.replace

    1.跳转到指定的URL,替换history栈中最后一个记录,点击后退会返回至上一个页面。(A----->B----->C 结果B被C替换 A----->C)
    2.设置replace属性(默认值:false)的话,当点击时,会调用router.replace(),而不是router.push(),于是导航后不会留下history记录。
    3.即使点击返回按钮也不会回到这个页面。加上replace: true时,它不会向 history 添加新纪录,而是跟它的方法名一样&mdash;&mdash;替换当前的history记录。

    // 声明式
    <reouter-link :to="..." replace></router-link>
    // 编程式:
    router.replace(...)
    // push方法也可以传replace
    this.$router.push({path: '/homo', replace: true})
    this.$router.replace({
        name: this.pageFrom,
        params: this.formData
    })
    onConfirm: () => {
      this.$router.replace('/TravelManage')
    }

    3、this.$router.go(n)

    1.向前或者向后跳转n个页面,n可为正整数或负整数

    2.this.$router.go(1) // 类似history.forward()

    3.this.$router.go(-1) // 类似history.back()

    总结区别:

    this.$router.push
    跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面

    this.$router.replace
    跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)

    this.$router.go(n)
    向前或者向后跳转n个页面,n可为正整数或负整数

    相关文章