vue-router传递参数组要有两种类型:params和query

params

  • 配置路由格式:/router/:id
  • 传递到方式:在path后跟上对应的值
  • 传递后形成的路径:/router/123,/router/abc

具体文章


query的类型:方式一

  • 配置路由格式:/router,也就是普通配置
  • 传递到方式:在对象中使用query的key作为传递方式
  • 传递后形成的路径:/router?id=123,/router?id=abc

我们要在Profile组件中获取根组件传递过来的数据

步骤:

  1. 创建路由组件
  2. 在路由中配置映射

     {
    
       path: '/profile',
       name: 'Profile',
       component: () => import('../views/Profile.vue')
     }
    
  3. 在跟组件中使用router-link

     //App.vue
     <template>
       <div id="app">
        <div id="nav">
           <router-link to="/">Home</router-link> |
           <router-link to="/about">About</router-link> |
           <router-link :to="{path:'/profile',query{name:'xiufan',age:21}}">Profile</router-link>
         </div>
         <router-view/>
       </div>
     </template>
    

使用v-bind为to属性绑定一个对象{path:'/path',query:{key:value}}

运行后url为:http://localhost:8080/profile?name=xiufan&age=21


在Profile.vue中获取query

//Profile.vue
<template>
    <div id="profile">
        <h1>this is profile page</h1>
        <p>name:{{name}}</p>
        <p>age:{{age}}</p>
    </div>
</template>

<script>
    export default {
       name: "Profile",
        data() {
            return {
                name : this.$route.query.name ,
                age : this.$route.query.age
            }
        }
    }
</script>

query的类型:方式二

不使用router-link
假如我们想点击一个按钮时跳转路由,并将参数传递过去

  • 可以为button添加一个点击事件,在事件方法中使用this.$router.push({path:'',query:{key:value}})
//App.vue
<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <button @click="profileClick">Profile</button>
    </div>
    <router-view/>
  </div>
</template>

<script>
  export default {
    name: 'App',
    data(){
      return{
        userId:"123"
      }
    },
    methods : {
        profileClick(){
          this.$router.push({
            path :'/profile',
            query : {
              name:'xiufan',
              age:21
            }
          })
        }
    }
  }
</script>

运行结果与方式一相同


其他vue-router文章

vue-router的安装和配置方式
将router修改为HTML5的history模式 & router-link的其他属性
vue的动态路由
vue的路由懒加载
vue路由的嵌套
vue-router参数传递
vue-router导航守卫
vue-router的keep-alive