vue路由传参方式的方式及获取参数的方法

发布时间:2022-07-29 17:40:07 作者:iii
来源:亿速云 阅读:188

这篇“vue路由传参方式的方式及获取参数的方法”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“vue路由传参方式的方式及获取参数的方法”文章吧。

一、声明式传参

1.params传参(显示参数)

在url中会显示出传参的值,刷新页面不会失去拿到的参数,使用该方式传值的时候,需要子路由提前配置好参数:

//路由参数配置
const router = new VueRouter({
  routes: [{
    path: '/about/:id',
    component: User
  }]
})
 
//声明式导航使用
<router-link to="/about/12">跳转</router-link>
//路由参数配置
const router = new VueRouter({
  routes: [{
    name: 'user1',
    path: '/about/:id',
    component: User
  }]
})
 
//声明式导航使用
<router-link :to="{ name: 'user1', params: { id: 123 } }">跳转</router-link>

2.params传参(不显示参数)

在url中不会显示出传参的值,但刷新页面会失去拿到的参数,使用该方式 传值 的时候,需要子路由提前配置好name参数:

//路由参数配置
const router = new VueRouter({
  routes: [{
    name: 'user1',
    path: '/about',
    component: User
  }]
})
 
//声明式导航使用
<router-link :to="{ name: 'user1', params: { id: 123 } }">跳转</router-link>

3.query 传参

query 传过去的参数会拼接在地址栏中(?name=xx),刷新页面数据不会丢失,使用path和name都可以:

//路由参数配置
const router = new VueRouter({
  routes: [{
    name: 'user1',
    path: '/about',
    component: User
  }]
})
 
//使用name
<router-link :to="{ name: 'user1', query: { id: 123 }}"></router-link>
//使用path
<router-link :to="{ path: '/about', query: { id: 123 } }"></router-link>

二、编程式传参

1.params传参(显示参数)

//路由配置
{
  path: '/child/:id',
  component: Child
}
//编程式使用
this.$router.push({
    path:'/child/${id}',
})
//路由配置
{
  path: '/child:id',
  component: Child,
  name:Child
}
//编程式使用
this.$router.push({
    name:'Child',
    params:{
    id:123
    }
})

2.params传参(不显示参数)

//路由配置
{
  path: '/child',
  component: Child,
  name:Child
}
//编程式使用
this.$router.push({
    name:'Child',
    params:{
    id:123
    }
})

3.query 传参

//路由配置
{
  path: '/child',
  component: Child,
  name:Child
}
//编程式使用
//name方式
this.$router.push({
    name:'Child',
    query:{
    id:1
}
})
//path方式
this.$router.push({
    path:'/child',
    query:{
    id:1
}
})

三、获取参数

1、params的获取方式

this.$route.params.xxx

2、query的获取方式

this.$route.query.xxx

四、需要注意的点

1、如果使用params传参,且参数是以对象的形式,跳转路径只能使用name形式而不能用path.

2、如果想要params参数想传参也可以不传参需要在占位符后面加?。

//路由参数配置
const router = new VueRouter({
  routes: [{
    path: '/search/:keyword?',
    name: 'search',
    component: () => import('@/pages/Search'),
    meta: { show: true }
  }]
})
//编程式传参
 this.$router.push({
    name: "search",
    params: {},
    query: { keyword: this.keyword },
 });

3、解决params传值为空字符串路径会出现问题:

 this.$router.push({
      name: "search",
      params: { keyword: "" || undefined },
      query: { keyword: this.keyword },
 });

以上就是关于“vue路由传参方式的方式及获取参数的方法”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. vue路由传参的基本实现方式小结【三种方式】
  2. vue路由传参三种基本方式详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:Spring框架IOC容器底层原理是什么

下一篇:Java图像处理之获取用户感兴趣的区域怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》