vue路由介绍及使用

vue-router:官方提供的vue路由插件
使用流程:
下载:npm I -S vue-router
引用:import VueRouter from 'vue-router'
注册:Vue.use(VueRouter)
路由配置:
const routes=[
{path:'/films',component:Films}, //path:路径 component:组件名
{path:'/cinemas',component:Cinemas},
{path:'/center',component:Center},
]
创建路由:
const router =new VueRouter({
routes
})
导出:export default router
使用路由:<router-view />
<router-view /> :路由容器,基于slot的封装
二级路由
二级路由是和一级路由是兄弟关系,跳转时页面会全部覆盖
const routes=[
{path:'/a',component:A},
{path:'/a/b',component:B}
]

嵌套路由
嵌套路由与一级路由是父子关系,可以实现局部跳转
const routes=[
{
path:'/films',
component:Films,
children:[
{path:'/film/nowplaying',component:NowPlaying},
{path:'/films/comingSoon',component:ComingSoon},
]
}
}
<router-link />:路由跳转,默认为a标签,tag="li"改变标签,to="路由"
activeClass="类名":指定激活后的样式,跳转路由自动激活css样式
重定向路由
redirect:{path: '/film',redirect: '/film/nowplaying'}

router-link编程式和声明式
声明式:<router-link :to="路由">
编程式:this.$router.push("路由")
this.$router.replace("路由") 替换一个路由 (不记录到历史记录)
this.$router.go() | back() 前进 | 返回

动态路由:
我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。
动态路由:xx/:变量/xx
路径的变量会设置在this.$route.params中
模式 匹配路径 $route.params
/user/:username /user/evan { username: 'evan' }
/user/:username/post/:post_id /user/evan/post/123 { username: 'evan', post_id: '123' }

history和hash:
创建路由时有一个mode属性,默认是hash,代表路径地址有"#",若想去掉需要改成 mode:history
但是history路径容易跟后台接口路径冲突,如果 URL 匹配不到任何静态资源,则需要后端返回同一个 index.html 页面
hash #/home
history /home

const router =new VueRouter({
mode:history
})
路由原理:
1. hash路由 ==> location.hash 切换
window.onhashchange 监听路径的切换
2. history路由==> history.pushState 切换
window.onpopstate 监听路径的切换
全家桶
vue cli
vue router
vuex

猜你喜欢

转载自www.cnblogs.com/maozo/p/12573780.html