一、 简介
路由是将hash地址与组件进行映射,下面#/A代表hash地址,一个页面可看成一个组件
<a href="#/A">A</a>
二、 动态组件切换路由
window.location.hash打印出当前hash地址,#/A,#/B
<template>
<div>
<a href="#/advise/A">A</a>
<a href="#/advise/A">B</a>
<hr />
<comment :is="col"></comment>
</div>
</template>
<script>
import A from './A.vue'
import B from './B.vue'
export default {
data() {
return {
col: 'A'
}
},
components: { A, B }
created() {
window.onhashchange = () => {
console.log('监听到了hash地址的变化', window.location.hash)
switch (location.hash) {
case '#/B':
this.col = 'B'
break
case '#/A':
this.col = 'A'
break
}
}
}
}
</script>
<style lang="scss" scoped></style>
三、声明式导航
点击链接的方式,普通网页叫<a>,vue项目叫router-link
a+router-view
<router-view></router-view>表示占位符
不用import,自动匹配index.js中路由
<template>
<div>
<a href="#/advise/A">A</a>
<a href="#/advise/A">B</a>
<hr />
<router-view></router-view>
</div>
</template>
<script>
</script>
router-link
<router-link></router-link>
a中才要加#,router-link路由不用加#,默认前面是#,但是去掉#/会变多一个后面的
<template>
<div>
<router-link to="/advise/A">A</router-link>
<router-link to="/advise/b">B</router-link>
</div>
</template>
<script></script>
A是去掉#/,直接advise/A,可以看出多一个,B中是去掉#,可以看出自动加#
四、嵌套路由
子路径要找对,找到自己页面对应的vue
跟上面的path要对应
五、动态路由
fullpath是完整的路径, query是携带的参数, 根据params设置动态
route文件下的index.js,path文件下A
六、编程时导航
浏览器中调用api方法实现导航的方式
this.$route是路由的参数对象
this.$route.push('/') 保留历史记录,后退键
this.$route.replace('/')不保留历史记录,无后退键
this.$route.go(1)向前一步,可正可负
this.$router是路由的导航对象
行内使用的时候,this去掉,否则报错
$router.back()向后
$router.forward()向前
七、导航守卫
控制路由访问的权限,常用于检测到未登录,强制到登录页面
可选三个参数,to,next,from
to: 即将要进入的目标from: 当前导航正要离开的路由next: 跳转的页面
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})