参数传递方法:
params的类型
1.配置路由格式 /router/:id
2.传递的方式:在path后面跟上对应的值
3.传递后形成的路径:/router/123
query的类型
1.配置路由格式:/router,普通的配置
2.传递的方式:query的key作为传递的方式
3.传递后形成的路径:/router?id=123
params传递:
1.在index.js配置路由
{
path: '/user/:userid',
component: User
}
2.在App.vue中配置路径
<template>
<div id="app">
<router-link v-bind:to='"/user/"+userid'>用户页面</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
userid:'hhhh'
}
},
}
</script>
<style>
</style>
3.在User.vue获取参数
<template>
<div>
<h2>用户页面</h2>
<!-- $route 是处于活跃状态的路由 -->
<h2>{{$route.params.userid}}</h2>
</div>
</template>
4.效果图
query传递
1.在index.js配置路由
{
path: "/profile",
component: Profile
}
2.在App.vue中配置路径
<template>
<div id="app">
<router-link :to='{path:"/profile",query:{name:"xh",age:18,sex:"boy"}}'>档案资料</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
</style>
3.在Profile.vue获取参数
<template>
<div>
<h2>用户档案资料</h2>
<h4>{{$route.query.name}}</h4>
<h4>{{$route.query.age}}</h4>
<h4>{{$route.query.sex}}</h4>
</div>
</template>
4.效果图
通过原生js的方法实现router-link
<template>
<div id="app">
<h2>hello world</h2>
<button @click='homeClick'>home</button>
<button @click='aboutClick'>about</button>
<button @click='userClick'>用户页面</button>
<button @click='profileClick'>用户档案</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
userid:'hhhh'
}
},
methods:{
homeClick(){
// 通过代码的方式修改路由 $router是new的router对象
this.$router.push('/home')
// this.$router.replace('/home')
},
aboutClick(){
this.$router.push('/about')
// this.$router.replace('/about')
},
userClick(){
this.$router.push('/user/' + this.userid)
},
profileClick(){
this.$router.push({
path:'/profile',
query:{
name:'lh',
age:22,
sex:"girl"
}
})
}
}
}
</script>
<style>
</style>
$router是new的router对象
$route 是处于活跃状态的路由