Skip to content

面经

介绍一下Vue-router的两种模式 × hash模式和history模式

均不会触发页面的重载

hash

  • # 之后的内容被称为哈希值(Hash Fragment)
  • 哈希值不会被包含在 HTTP 请求中,因此不会触发页面的重新加载,而只会触发浏览器的滚动事件

优点:

  • 兼容性好

缺点:

  • 用户不适应

history

  • HTML5 History API 中的 history.pushState()history.replaceState() 方法来管理浏览器的历史记录,从而实现路由的切换和导航

优点

  • 兼容性差(适用于现代浏览器
  • 美观

缺点:

  • 需要后端配置

基础

  • router

    • index.js设置路由规则

      js
      import { createRouter ,createWebHistory} from 'vue-router'
      import Home from '../views/Home.vue'
      import Article from '../views/Article.vue'
      
      const router = createRouter({
        history: createWebHistory(),
        routes:[
          {
            path:'/',
            name:'home',
            component:Home
          },
          {
            path:'/article',
            name:'article',
            component:Article
          }
        ]
      })
      export default router

      v

  • views

    • 设置渲染的页面(组件)
  • App.vue

    • 注册使用

      <router-link to=""></router-link>
      <router-view></routerview>
yarn add vue-router@4
import {createRouter} from 'vue-router'
import {createWebHistory,createWebHashHistory}

createWebHistory 使用首页渲染vue,对SEO更好,但有与后台地址冲突的隐患
createWebHashHistory 使用锚点渲染vue,对SEO不友好

使用路由前缀
  • 连接跳转

    <router-link to=""></router-link>
  • 视图渲染

    <router-view>

切换点击时的颜色

  • 打开chrome,调试找到相对应的css类名---使用系统提供的类

    <template>
      <div class="navigation">
        <router-link :to="{ name: 'home' }">Home</router-link>
        <router-link :to="{ name: 'article' }">Article</router-link>
      </div>
    </template>
    
    <script setup lang="ts">
    
    </script>
    
    <style lang="scss" scoped>
    .navigation {
      a {
        background-color: #fdcb6e;
        padding: 5px 10px;
        color:#dfe6e9;
        &.router-link-active {
          color: white
        }
      }
    }
    </style>
  • 使用props

    嵌套路由
    非嵌套路由
  • linkActive class

    • 父子级关系中存在
  • linkExractActive class

    • 明确点击的
    • 在路由配置中,可以修改linkExtractActiveClass

  • 别名 alias

    • vite.config.ts中设置alias别名,省去相对路径的问题

       import path from 'path'
      
       resolve: {
          alias: { '@': path.resolve(path.resolve(__dirname,'src')) }
        }

视图

使用视图,说白了就是在渲染组件的时候增添判断

        <router-view name="navigation" #default="{Component}">
          <component :is="Component ?? navigation"></component>
        </router-view>

路由跳转

钩子函数:

  • 组件守卫

    beforeRouteEnter		其它的路由进入到此路由的之前   这时
    beforeRouteUpdate
    beforeRouteLeave
  • 全局守卫

    beforeEach				全局前置
    beforeResolve			全局解析
    afterEach				全局后置
  • 路由守卫

    beforeEnter

情况一:跳转页面,路由改变的时候

  • 全局守卫的三个必然执行

    beforeEach
    beforeResolve
    afterEach

情况二:渲染当前页面,仅参数发生变化时

  • 只执行全局守卫+组件更新守卫

    beforeEach
    beforeRouteUpdate
    beforeResolve
    afterEach

其它情况:

离开
beforeRouterLeave
全局+路由+组件
beforeEach
beforeEnter
beforeRouteEnter
beforeResolve
afterEach

watch监听中的渲染时就立即执行

watch(obj,()=>{},{immediate: true})