一、基础概念
Vue Router是Vue.js官方的路由管理器,可以让我们通过组件化的方式构建单页应用,根据不同的路径展示不同的组件。在Vue Router中,我们可以通过props属性将路由参数传递给需要展示的组件。
// example
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/user/:id',
component: User,
props: true // 将路由参数作为props传递给组件
}
]
const router = new VueRouter({
routes
})
const User = {
props: ['id'],
created () {
getUser(this.id)
}
}
二、使用场景
1. 组件内部直接使用
我们可以在组件内部,通过props属性直接接收路由参数并使用。
// example
const User = {
props: ['id'],
created () {
getUser(this.id)
}
}
2. 组件间传递参数
在Vue Router中,我们可以通过props将路由参数传递给需要展示的组件。这样,我们就可以实现组件间传递参数的功能。
<!-- 父组件 -->
<template>
<router-link :to="{ name: 'user', params: { id: userId }}">查看用户信息</router-link>
</template>
<!-- 子组件 -->
<template>
<div>{{ user.name }}</div>
</template>
<script>
export default {
props: ['id'],
data () {
return {
user: {}
}
},
created () {
this.getUserInfo(this.id)
},
methods: {
getUserInfo (id) {
// 发送请求获取用户信息
this.user = res.data
}
}
}
</script>
3. 动态路由
在实际开发中,我们有时需要根据不同的路由参数展示不同的组件。Vue Router提供了动态路由功能,可以根据路由参数动态地展示不同的组件。
// example
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: User,
props: true
}
]
})
三、props选项
在Vue Router中,我们可以通过props选项将路由参数作为组件的props传递,props选项有以下几种使用方式:
1. Boolean类型
若props设置为true,则会将路由参数作为组件的props传递,我们可以在组件内部通过props接收参数。
// example
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: User,
props: true
}
]
})
2. Object类型
我们也可以利用Object类型的props选项,手动映射路由参数和组件props的关系。
// example
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: User,
props: { // 映射路由参数和组件props的关系
id: 'userId'
}
}
]
})
// User组件
export default {
props: ['userId'],
created () {
console.log(this.userId) // 输出路由参数中的id
}
}
3. Function类型
我们可以通过Function类型的props选项,手动处理路由参数并将其作为组件的props传递。
// example
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: User,
props: (route) => ({ // 手动处理路由参数并将其作为props传递
id: parseInt(route.params.id)
})
}
]
})
// User组件
export default {
props: ['id'],
created () {
console.log(this.id) // 输出处理后的路由参数
}
}
四、总结
通过Vue Router的props选项,我们可以实现将路由参数传递给组件的目的,使得我们能够轻松地在单页应用中展示不同的组件,实现更加灵活多变的功能和效果。