this.$router.push跳转页面携带参数

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

this.$router.push进行页面跳转时。携带参数有params和query两种方式。

一、params和query使用方式

query方式:
this. r o u t e r . p u s h ( p a t h : ′ t e s t Q u e r y ′ , q u e r y : t e s t Q u e r y : ′ t e s t Q u e r y ′ ) , 传 递 的 参 数 会 拼 接 在 跳 转 地 址 的 后 面 。 使 用 t h i s . router.push({path: 'testQuery',query: {testQuery:'testQuery'}}),传递的参数会拼接在跳转地址的后面。使用this. router.push(path:testQuery,query:testQuery:testQuery)使this.route.params.key取值
params方式:
this. r o u t e r . p u s h ( n a m e : ′ t e s t P a r a m s ′ , p a r a m s : t e s t P a r a m s : ′ t e s t P a r a m s ′ ) , 传 递 的 参 数 不 会 拼 接 在 跳 转 的 后 面 。 使 用 t h i s . router.push({name: 'testParams',params: {testParams:'testParams'}}),传递的参数不会拼接在跳转的后面。使用this. router.push(name:testParams,params:testParams:testParams)使this.route.query.key取值

二、实现代码

1.index.js代码

const router = new Router({
    routes: [
        {
            path:'/test',
            component: test,
        },
        {
            name: 'testParams',
            path:'/testParams',
            component: TestParams,
        },
        {
            path:'/testQuery',
            component: TestQuery,
        }
    ]
})

2.test.vue代码

<template>
  <div class="test">
    <button v-on:click="testParams">params</button>
    <button v-on:click="testQuery">query</button>
  </div>
</template>
<script>
export default {
  name: "test",
  data(){
    return {

    }
  },
  methods:{
    testParams(){
      this.$router.push({name: 'testParams',params: {testParams:'testParams'}});
    },
    testQuery(){
      this.$router.push({path: 'testQuery',query: {testQuery:'testQuery'}});
    }
  }
}
</script>

3.testParams代码

<template>
  <div id="testParams">
    {{testParams}}
  </div>
</template>

<script>
export default {
  name: "TestParams",
  data() {
    return{
      testParams: ''
    }
  },mounted() {
    this.testParams = this.$route.params.testParams;
  }
}
</script>

4.testParams代码

<template>
  <div id="testQuery">
    {{testQuery}}
  </div>
</template>

<script>
export default {
  name: "TestQuery",
  data(){
    return{
      testQuery: ''
    }
  },mounted() {
    this.testQuery = this.$route.query.testQuery;
  }
}
</script>

5.效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

两种方式非常相似,区别在于两点:
1、是否在地址后面拼接参数。
2、因为动态路由也是传递params的,所以在 this.$router.push() 方法中 path是不能和params一起使用的,否则params将无效。需要用name来指定页面,一定要记得,在index.js中设置好那么属性。

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值