vue-router传递参数方法(3种)

第一种:get方法

传递值

<router-link :to="{path:'/test',query: { userId: 123,userName:'xia' }}">跳转</router-link>
或
<router-link :to="{name:'test',query: { userId: 123,userName:'xia' }}">跳转</router-link>

接收值(页面刷新的时候不会消失)

this.$route.query.userId  // 123
this.$route.query.userName  // xia

url上显示参数:http://localhost:8080/test?userId=123&userName=xia


第二种:post方法

传递值

<!-- 必须用 name:'test' -->
<router-link :to="{name:'test',params: { userId: 123,userName:'xia' }}">跳转</router-link>

<!-- 用 path:'/test' 无效 -->
<!-- <router-link :to="{path:'/test',params: { userId: 123,userName:'xia' }}">跳转</router-link> -->

接收值(页面刷新的时候就会消失)

this.$route.params.userId  // 123
this.$route.params.userName  // xia

url上不显示参数:http://localhost:8080/test


第三种:路由方法

传递值

// router.js
{
    path: '/test/:userId/:userName?', //?问号的意思是该参数不是必传项
    name: 'test',
    component: 'test.vue',
    props: true,
},
// App.vue
<router-link to="/test/123/xia">跳转</router-link>

接收值(页面刷新的时候不会消失)

this.$route.params.userId  // 123
this.$route.params.userName  // xia

url上显示参数:http://localhost:8080/test/123/xia

注意:

(1)

上文中router-link中的path和name都是路由里面的,页面创建成功后一定要配置页面的路由;

上文中第三种方法,还在路由中也进行了相应的配置;

路由中的配置:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/get',
      name:'get',
      component: resolve => require(['../components/get.vue'], resolve),
      meta: {
        title: 'get'
      },
    },
    {
      path: '/post',
      name:'post',
      component: resolve => require(['../components/post.vue'], resolve),
      meta: {
        title: 'post'
      },
    },
    {
      path: '/route/:rouId/:rouName?'
      name:'route',
      component: resolve => require(['../components/route.vue'], resolve),
      meta: {
        title: 'route'
      },
    }
  ]
})


另外: 如果在链接上设置 replace 属性,当点击时,会调用 router.replace() 而不是 router.push(),于是浏览器不会留下 history 记录。(无法返回到上一页)

  <router-link :to="{ path: '/test'}" replace></router-link>

Tips:这里我简单说明下 $router 和 $route 的区别:

  1. $router :是指整个路由实例,你可以操控整个路由,用法如下:
    this.$router.go(-1);  // 向前或者向后跳转n个页面,n可为正整数或负整数
    this.$router.push('/'); // 跳转到指定url路径,history栈中会有记录,点击返回会跳转到上个页面
    this.$router.replace('/'); // 跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面
    
  2. $route:是指当前路由实例$router跳转到的路由对象;路由实例可以包含多个路由对象,它们是**父子包含关系**.
    // 获取路由传递过来的参数
    this.$route.params.userId  
    this.$route.query.userName 
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值