vue-router参数传递

119 阅读1分钟

1、params传递参数

传参

//Home.vue
<router-link :to="'/home/friends/' + userid">好友</router-link>

data() {
    return {
      userid: "wecle",
    };
},

路由

//index.js
{
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: 'friends/:userid',
        name: 'Friends',
        component: Friends
      },
    ]
},

接收参数

//Friends.vue
<template>
  <div>
    <h1>这是好友插件</h1>
    <h2>{{ userId }}</h2>
  </div>
</template>

<script>
export default {
  name: "friends",
  computed: {
    userId() {
      return this.$route.params.userid;
    },
  },
};
</script>

image.png

2、query传递参数

传参

//Home.vue
<router-link :to="{ path: '/home/profile', query: { name: 'wecle', age: 18 } }">个人</router-link>

//或者使用button或者a进行传递
<button @click="profileClick()">个人</button>

methods: {
    profileClick() {
      this.$router.push({
        path: "/home/profile",
        query: {
          name: "wecle",
          age: 18,
        },
      });
    },
},

路由

//index.js
{
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: 'profile',
        name: 'Profile',
        component: Profile
      }
    ]
},

接收参数

//Profile.vue
<template>
  <div>
    <h1>这是个人插件</h1>
    <h2>{{ queryClick.name }}</h2>
    <h2>{{ queryClick.age }}</h2>
  </div>
</template>

<script>
export default {
  name: "profile",
  data() {
    return {};
  },
  computed: {
    queryClick() {
      return this.$route.query;
    },
  },
};
</script>

image.png