传递参数主要有两种类型
params和query
params的类型:
配置路由格式:/router/:id
传递的方式:在path后面跟上对应的值
传递后形成的路径:/router/123,/router/abc
取值:$route.params.id
router/index.js
{
path: '/home/:id',
name: 'Home',
component: () => import("@/components/Home"),
meta: {
title: '首页'
}
},
Home.vue
<template>
<div>
<h1>我是首页</h1>
<h2>{{$route.params.id}}</h2>
</div>
</template>
<script>
export default {
name: "Home"
}
</script>
<style scoped>
</style>
App.vue
声明式:
<router-link :to="'/home/'+userId" tag="button" replace>首页</router-link>
homeclick() {
// this.$router.push("/home");
this.$router.replace("/home"+ this.userId);
},
query的类型:
配置路由格式:/router,也就是普通配置
传递的方式:对象中使用query的key作为传递方式
传递后形成的路径:/router?123,/router?id=abc
取值:$route.query.name
router/index.js
{
path: '/profile',
name: 'Profile',
component: () => import("@/components/Profile"),
meta: {
title: '档案'
}
},
Profile.vue
<template>
<div>
<h2>我是Profile</h2>
<h3>{{ $route.query.name }}</h3>
<h3>{{ $route.query.age }}</h3>
</div>
</template>
<script>
export default {
name: "Profile"
}
</script>
<style scoped>
</style>
App.vue
声明式:
<router-link :to="{path:'/profile',query:{name:'why',age:18}}">点击一下</router-link>
Profileclick() {
this.$router.push({
path: '/profile',
query: {
name: 'kobe',
age: 18
}
});
}