假设我们有一个Vue应用程序,需要展示不同用户的个人资料页面。我们可以使用Vue-router的动态路由来达到这个目的,它允许我们根据不同的URL参数动态地加载不同的组件,并且可以获取传递的值。例如:
我们的路由配置如下:
const router = new VueRouter({
routes: [
{
path: '/profile/:userId',
name: 'UserProfile',
component: UserProfile
}
]
})
在这里,我们使用了动态路由参数 :userId
,它表示我们可以通过URL参数来访问不同的用户个人资料页面。同时,我们也指定了路由名称 UserProfile
和所对应的 Vue 组件 UserProfile
。
接下来,我们在 UserProfile
组件中获取路由参数 userId
的值,以便展示对应用户的资料信息:
<template>
<div>
<h1>User Profile</h1>
<p>id: {{ userId }}</p>
<p>name: {{ username }}</p>
<p>email: {{ email }}</p>
</div>
</template>
<script>
export default {
name: 'UserProfile',
data () {
return {
userId: '',
username: '',
email: ''
}
},
created () {
this.userId = this.$route.params.userId
// 此处可以根据userId获取对应用户的相关信息,这里只做模拟
this.username = 'testuser' + this.userId
this.email = 'testuser' + this.userId + '@example.com'
}
}
</script>
在这里,我们使用了 created
生命周期钩子,在组件创建时从路由参数中获取 userId
的值,并将其赋值给组件的数据 userId
。同时,我们还模拟了根据 userId
获取对应用户的相关信息,并将其展示在页面中。