什么是前端路由

通俗易懂的概念: Hash 地址组件之间的对应关系

前端路由的工作方式

1⃣ 用户点击了页面上的路由链接
2⃣️ 导致了 URL 地址栏中的 Hash 值发生了变化
3⃣️ 前端路由监听到了Hash 值的变化
4⃣️ 前端路由把当前 Hash 地址对应的组件 渲染到浏览器中
image.png

Vue-router 的基本用法 、 安装配置

1、什么是 vue-router
image.png
vue-router 的官方文档地址 https://router.vuejs.org/zh/

2、vue-router 安装和配置步骤
image.png
image.png
image.png

路由的基本使用

在router/index.js下配置完成以后要在 main.js 继续配置 调用 属性名和属性值一样可以简写
image.png
配置完成main.js后 继续在 router/index.js 里面添加内容
image.png
在app.vue里面配置
image.png

  1. <!-- 当安装和配置了 vue-router 后, 就可以使用 router-link 来代替普通的 a 链接 -->
  2. <!-- <a href="#/home">首页</a> -->
  3. <router-link to="/home">首页</router-link>

路由重定向 就是默认访问的是 / 没有定义 所以要让他跳转到首页
image.png

嵌套路由

image.png
image.png
子路由不需要前面加 /
// 默认子路由: 如果 children 数组中, 某个路由规则的 path 值为空字符串, 则这条路由规则, 叫做“默认子路由”

动态路由

4.1 动态路由的概念
image.png
具体操作
第一步在 根目录 App.vue里面
image.png
第二步在 router/index.js 里面绑定动态id
image.png
第三步在 Movie.vue 里面获取到 this值, 值里面包含this.$route.params.id // this可以省略
image.png
两种动态路由都可以实现
image.png

编程式导航

image.png
image.png
image.png

  1. <template>
  2. <div class="home-container">
  3. <h3>Home 组件</h3>
  4. <hr />
  5. <button @click="gotoLk">通过 push 跳转到'洛基'页面</button>
  6. <button @click="gotoLk2">通过 replace 跳转到'洛基'页面</button>
  7. <!-- 在行内使用编程式导航跳转的时候, this必须要省略, 否则会报错! -->
  8. <button @click="$router.back()">back 后退</button>
  9. <button @click="$router.forward()">forward 前进</button>
  10. <button>
  11. </div>
  12. </template>
  13. <script>
  14. export default {
  15. name: 'Home',
  16. methods:{
  17. gotoLk(){
  18. // 通过编程式导航 API, 导航跳转到指定的页面 有后退路径
  19. this.$router.push('/movie/1')
  20. },
  21. gotoLk2(){
  22. this.$router.replace('/movie/1') // 无后退路径
  23. }
  24. }
  25. }
  26. </script>

全局前置导航守卫

image.png
下面这个全局守卫应该在 router/index.js 里面设置
image.png
image.png

image.png
router/index.js 里面设置
image.png