vue router 配置路由的方法
用 Vue.js + vue-router 创建单页应用,是非常简单的。使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 vue-router 添加进来,我们需要做的是,将组件(components)映射到路由(routes),然后告诉 vue-router 在哪里渲染它们。
路由的基本实现
Document
home
about
重定向
解释:将 / 重定向到 /home
{ path: '/', redirect: '/home' }
路由导航高亮
说明:当前匹配的导航链接,会自动添加router-link-exact-active router-link-active类
路由参数
说明:我们经常需要把某种模式匹配到的所有路由,全都映射到同一个组件,此时,可以通过路由参数来处理
语法:/user/:id
使用:当匹配到一个路由时,参数值会被设置到 this.$route.params
其他:可以通过 $route.query 获取到 URL 中的查询参数 等
// 链接:
用户 Jack
用户 Rose
// 路由:
{ path: '/user/:id', component: User }
// User组件:
const User = {
template: `User {{ $route.params.id }}
`
}
嵌套路由 - 子路由
Vue路由是可以嵌套的,即:路由中又包含子路由
规则:父组件中包含 router-view,在路由规则中使用 children 配置
// 父组件:
const User = Vue.component('user', {
template: `
User Center
个人资料
岗位
`
})
// 子组件:
const UserProfile = {
template: '个人资料:张三
'
}
const UserPosts = {
template: '岗位:FE
'
}
{ path: '/user', component: User,
// 子路由配置:
children: [
{
// 当 /user/profile 匹配成功,
// UserProfile 会被渲染在 User 的 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/posts 匹配成功
// UserPosts 会被渲染在 User 的 中
path: 'posts',
component: UserPosts
}
]
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。