Vue学习-- Vue Router 参数传递params和query

版权声明:本博客为博主原创,转载请注明出处 https://blog.csdn.net/qq_38045106/article/details/84037530

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。


方法一

param传递参数(get方式)

getDescribe(id) {
    //直接调用$router.push 实现携带参数的跳转
    this.$router.push({
    path: `/describe/${id}`,
    //this.$router.push({ name: 'user', params: { userId }}) // -> /user/123
 })
//需要路由中进行如下配置
{
     path: '/describe/:id',
     name: 'Describe',
     component: Describe
}
//取出参数
this.$route.params.id
  1. 使用这种传参方式,要在路由中进行配置(如"/:id"),params是路由的一部分(地址栏中显示/describe/id的形式),必须要在路由后面添加参数名。params一旦设置在路由,params就是路由的一部分,如果这个路由有params传参,但是在跳转的时候没有传这个参数,会导致跳转失败或者页面会没有内容。
  2. 使用params传参只能用name来引入路由,即push里面只能是name:’xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined(由于动态路由也是传递params的,所以在 this.$router.push() 方法中 path不能和params一起使用,否则params将无效
  3. 如果路由中不进行/:id的配置,页面的第一次跳转正常,地址栏中没有参数,但是一刷新页面就不会接受到参数
  4. 如果参数不是必传的参数,可进行如下配置
//需要路由中进行如下配置
{
     path: '/describe/:id?',
     name: 'Describe',
     component: Describe
}

如果 props 被设置为 trueroute.params 将会被设置为组件属性。请看如下代码

//?问号的意思是该参数不是必传项
//多个参数用/:id连接
//path: '/Driver/CarManager/CarSetting/:car_id/:page_type',
{
    path: 'test/:name?',
    name: 'test',
    component: 'test.vue',
    props: true,
},
props:{name:{required:false,default:''}} (页面刷新不消失,可以在路由配置中设置参数)

方法二

使用query进行传递(post方式)

//传参时
this.$router.push({
    path: '/describe',
    query: {
        id: id
    }
})
//路由中的配置(和不传参的一样哈)
   {
path: '/describe',
    name: 'Describe',
    component: Describe
}
//取出参数时
this.$route.query.id
  1. query传递参数的方式,参数显示在地址栏中(如地址栏显示"/describe?id=88"),类似get方式,通过URL传参
  2. query传递参数用path和那么的方式都可以,参数可以不传

猜你喜欢

转载自blog.csdn.net/qq_38045106/article/details/84037530