Vue跳转URL与参数传递

写业务中,从一个页面跳转到另一个页面,经常需要传值和取值,如何实现?

1、通过router-link进行跳转

  1. 使用query传递参数,路由必须使用path引入

    <-- 在a页面进行传值 -->
        
    <router-link :to="{path: '/home', query: {key: 'hello', value: 'world'}}">
      <button>跳转</button>
    </router-link> 
    

    跳转地址 => /home?key=hello&value=world

    在b页面取值: this.$route.query.key

  2. 使用params传递参数,路由必须使用name引入

    <-- 在a页面进行传值 -->
        
    <router-link :to="{name: '/home', params: {key: 'hello', value: 'world'}}">
      <button>跳转</button>
    </router-link> 
    

    跳转地址 ==> /home

    在b页面取值:this.$route.params.key

2、$router方式跳转

  1. 通过query

    this.$router.push({
      path: '/detail',
      query: {
        name: 'admin',
        code: 10021
      }
    }); 
    

    跳转地址 => /detail?name=admin&code=10021

    取值:this.$route.query.name

3、跳转外部链接

如果是vue页面中的内部跳转,可以用this.$router.push()实现,但是如果用这种方法跳到外部链接,就会报错,原因是直接把外部链接加在了http://localhost:8080/#/的后面,这就导致跳转出现问题。那么如何跳转到外部链接呢,其实只需用 window.location.href = ‘url’就能实现。

具体代码如下:html <span @click="See(url)">点击转跳</span>
上面是触发一个点击事件,其中url是传给see的url链接,下面是事件执行的函数
js See(e) { window.location.href = e }


感谢大家的耐心阅读,如有建议请私信或评论留言

posted @ 2022-11-16 18:05  杨业壮  阅读(2461)  评论(0编辑  收藏  举报