vue-router | 8月更文挑战

375 阅读4分钟

vue-router实现原理

SPA(single page application):单一页面应用程序,只有一个完整的页面;它在加载页面时,不会加载整个页面,而是只更新某个指定的容器中内容。单页面应用(SPA)的核心之一是:更新视图而不重新请求页面;vue-router在实现单页面前端路由时,提供了两种方式:Hash模式和History模式。

1、hash模式

随着 ajax 的流行,异步数据请求交互运行在不刷新浏览器的情况下进行。而异步交互体验的更高级版本就是 SPA —— 单页应用。单页应用不仅仅是在页面交互是无刷新的,连页面跳转都是无刷新的,为了实现单页应用,所以就有了前端路由。类似于服务端路由,前端路由实现起来其实也很简单,就是匹配不同的 url 路径,进行解析,然后动态的渲染出区域 html 内容。但是这样存在一个问题,就是 url 每次变化的时候,都会造成页面的刷新。那解决问题的思路便是在改变url的情况下,保证页面的不刷新。在 2014 年之前,大家是通过 hash 来实现路由,url hash 就是类似于:

http://www.xxx.com/#/login

这种 #。后面 hash 值的变化,并不会导致浏览器向服务器发出请求,浏览器不发出请求,也就不会刷新页面。另外每次 hash 值的变化,还会触发hashchange 这个事件,通过这个事件我们就可以知道 hash 值发生了哪些变化。然后我们便可以监听hashchange来实现更新页面部分内容的操作:

function matchAndUpdate () {
   // todo 匹配 hash 做 dom 更新操作
}

window.addEventListener('hashchange', matchAndUpdate)

2、history 模式

14年后,因为HTML5标准发布。多了两个 API,pushState 和 replaceState,通过这两个 API 可以改变 url 地址且不会发送请求。同时还有popstate事件。通过这些就能用另一种方式来实现前端路由了,但原理都是跟 hash 实现相同的。用了HTML5的实现,单页路由的url就不会多出一个#,变得更加美观。但因为没有 # 号,所以当用户刷新页面之类的操作时,浏览器还是会给服务器发送请求。为了避免出现这种情况,所以这个实现需要服务器的支持,需要把所有路由都重定向到根页面。

function matchAndUpdate () {
   // todo 匹配路径 做 dom 更新操作
}

window.addEventListener('popstate', matchAndUpdate)

vue-router 安装与使用

安装新版的 vue router

 npm install vue-router

vue-router 配置路由

 import { createRouter, createWebHistory } from 'vue-router'
 import Home from './views/Home.vue'
 import Login from './views/Login.vue'
 
 const routerHistory = createWebHistory()
 const router = createRouter({
   history: routerHistory,
   routes: [
     {
       path: '/',
       name: 'home',
       component: Home
     },
     {
       path: '/login',
       name: 'login',
       component: Login
     }
   ]
 })

vue-router 添加路由

 import { useRoute } from 'vue-router'
 // 它是一个函数,调用后可以返回对应的对象。
 const route = useRoute() 
 // 我们返回出去,在页面中把它全部显示出来看看
 return {
  route
 }

router-link 组件跳转的方式

我们第一种方法可以将 to 改成不是字符串类型,而是 object 类型,这个object 应该有你要前往route 的 name ,还有对应的 params。

  :to="{ name: 'column', params: { id: column.id }}"

第二种格式,我们可以在里面传递一个模版字符串,这里面把 column.id 填充进去就好。

  :to="`/column/${column.id}`"

使用 useRouter 钩子函数进行跳转

 const router = useRouter()
 // 特别注意这个是 useRouter 而不是 useRoute,差一个字母,作用千差万别,那个是获得路由信息,这个是定义路由的一系列行为。在这里,我们可以掉用
 router.push('/login') 
 ​
 // router.push 方法跳转到另外一个 url,它接受的参数和 router-link 的 to 里面的参数是完全一致的,其实router link 内部和这个 router 分享的是一段代码,可谓是殊途同归了。

添加导航守卫

router.beforeEach((to, from, next) => {
  if (to.name !== 'login' && !store.state.user.isLogin) {
    next({ name: 'login' })
  } else {
    next()
  }
})

添加元信息完成权限管理

添加元信息

  {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { redirectAlreadyLogin: true }
    },
    {
      path: '/create',
      name: 'create',
      component: CreatePost,
      meta: { requiredLogin: true }
    }

更新路由守卫

router.beforeEach((to, from, next) => {
 console.log(to.meta)
 if (to.meta.requiredLogin && !store.state.user.isLogin) {
   next({ name: 'login' })
 } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
   next('/')
 } else {
   next()
 }
})