vue-router的實現原理以及使用方法講解

 

vue中的vue-router是通過hashhistory兩種模式實現前端跳轉路由,更新視圖但不重新請求頁面”是前端路由原理的核心之一,實現主要有兩種方式

  1. hash ---- 利用URL中的hash(“#”)

  2. 利用History interface在 HTML5中新增的方法

實現方式首先在router/index.js中註冊路由 Vue.use(Router)

這裏把路由單獨寫在一個routes.js中並導出,注意別忘了導出 export default routes

const routes = [
  {
    path: '/',
    redirect: '/routerTest'
  },
  {
    path: '/routerTest',
    component: () => import('../components/recommend/view.vue')
  },
  {
    path: '/singer',
    component: () => import('../components/singer/view.vue')
  },
  {
    path: '/rank',
    component: () => import('../components/rank/view.vue')
  },
  {
    path: '/search',
    component: () => import('../components/search/view.vue')
  }
]
export default routes
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'

Vue.use(Router)

export default new Router({
  // mode: 'history',//兩種模式hash和history
  routes
})

這兩種方式有什麼區別呢

1.mode:'hash' 多了個# 前端路由不刷新頁面

http://localhost:8080/#/routerTest

 

2.mode:'history' 會去請求接口

http://localhost:8080/routerTest

 來看下實現不同模式跳轉路由的源碼

 // 根據mode確定history實際的類並實例化    

// 根據mode確定history實際的類並實例化
switch (mode) {
  case 'history':
    this.history = new HTML5History(this, options.base)
    break
  case 'hash':
    this.history = new HashHistory(this, options.base, this.fallback)
    break
  case 'abstract':
    this.history = new AbstractHistory(this, options.base)
    break
  default:
    if (process.env.NODE_ENV !== 'production') {
      assert(false, `invalid mode: ${mode}`)
    }
}

 HashHistory和HTML5History有什麼區別

hashhistory將路由添加到瀏覽器的棧頂 push

html5history將路由在瀏覽器中替換 replace

以上是vue-router的實現原理,接下來如何在項目中使用vue-router呢

vue的router-link和router-view,是實現vue-router的兩個必不可缺的組件,分別實現跳轉路由和展示路由
首先在main.js入口文件中配置router實例

舉個栗子

點擊跳轉C就切換到了LayOut組件的頁面

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章