Vue-Router

Router

SPA ( single page App ) 單頁面應用

  1. 多頁面應用
    有多個html文件,經過a標籤的鏈接聯通各個頁面
  • 缺點
    • 開發起來太冗餘,編譯、壓縮很耗時間
    • 頁面之間的跳轉速度太慢
  1. 單頁面應用
  • 不須要刷新頁面,由於它就是一個頁面
  • 這個頁面內容在切換
  • 單頁面內容之間的切換要想實現咱們就是用路由了
  • 現在咱們的app主要的開發形式就是spa

vue路由功能

  1. 實現單頁面的切換
  2. 路由攜帶參數
  3. 路由的導航守衛
  4. 路由進行數據預載(進入組件前就請求得到數據)

vue-router 基礎

  1. vue 路由的mode(模式)有幾種, 分別是什麼?在那些環境下運行?javascript

    • hash: 使用 URL hash 值來做路由。支持全部瀏覽器,包括不支持 HTML5 History Api 的瀏覽器。 /#home
    • history: 依賴 HTML5 History API 和服務器配置。【須要後端支持】 /home
    • abstract: 支持全部 JavaScript 運行環境,如 Node.js 服務器端。若是發現沒有瀏覽器的 API,路由會自動強制進入這個模式。【 這個模式不經常使用 】
  2. 路由的使用步驟html

    1. 安裝 vue-router yarn add vue-router -Svue

    2. 在src目錄下建立一個router目錄, 裏面建立一個index.js文件 , 這個目錄就是router的模塊java

    3. 引入第三方的依賴包, 並註冊路由android

      import Vue from 'vue'
        import VueRouter from 'vue-router'
      
        Vue.use( VueRouter ) //使用vue-router這個第三方插件

      注意: import這個關鍵字要放在整個文件的上層vue-router

    4. 建立了一個router對象實例,而且建立路由表編程

      const routes = [ 
          {
            path: '/home',
            component: Home
          }//每個對象就是一個路由
        ]
        const router = new VueRouter({
          routes//路由表  必寫的
          mode: 'history' //(設置好路由的模式有hash ,history)不設置這個會出現#
        })
    5. 導出router實例
      export default router後端

    6. 入口文件main.js中引入路由實例 router , 而後在根實例中註冊api

      import router from './router/index.js'
        new Vue({
          router,
          render: (h) => App 
        }).$mount('#app')
    7. 給路由一個路由展現區域瀏覽器

      1. 若是是以及路由, 那麼咱們放在App組件中,用一個 router-view 的組件表示
      <router-view />
    8. 當頁面第一次的打開的時候, 須要作一個重定向, 就是要自動跳轉到 /home 這個路由上

      const routes = [
            { //咱們要求這個路由的配置要放在路由表的最上方
              path: '/',
              redirect: '/home'
            }
          ]
    9. 業務: 錯誤路由匹配,

      const routes = [
            {
              path: '/',
              redirect: '/home'   //重定向
            },
            {
              path: '/home',
              component: Home
            },
            {
              path: '/list',
              component: List
            },
            {
              path: '/detail',
              component: Detail
            },
            {
              path: '/login',
              component: Login
            },
            {
              path: '/register',
              component: Register
            },
            {
              path: '/user',
              component: User
            },
            {
              path: '/shopcar',
              component: Shopcar
            },
            {
              path: '/error',
              component: Error
            },
            {  //這個就是錯誤路由匹配, vue規定這個必須放在最下面,它必須將上面的路由全找一遍,找不到才用當前這個
              path: '**',
              redirect: '/error'
            }
          ]
    10. vue路由模式的肯定 mode

    11. 若是你使用的是 hash , 那麼a標籤就能夠了、

    12. 若是你使用 history , 那麼咱們最好將a標籤改爲 router-link 這個組件

      • router-link 這個組件 身上必需要有一個 to 屬性
      • router-link 這個組件身上加一個 keep-alive屬性能夠進行瀏覽器緩存
    13. 二級路由

    const routes = [
             {
               path: '/shopcar',
               component: Shopcar,
               children: [
                 {
                   path: 'yyb', //不寫  /
                   component: Yyb
                 }
               ]
             }
           ]
    • 注意: 寫好配置以後,不要忘記了, 在對應的一級路由的組件中書寫 路由展現區域
    1. 命名路由

      做用: 就是簡寫路徑了

      {
            path: '/shopcar',
            component: Shopcar,
            //子路由 
            children: [
              { 
                path: 'yyb', // 容易犯錯點  /yyb X 
                component: Yyb,
                name: 'yyb' //命名路由
              },
              {
                path: 'junge',
                component: Junge
              }
            ]
      
          },
      • 使用:

        <router-link :to = "{name:'yyb'}"/>

vue-router 進階

動態路由 & 路由傳參 & 路由接參

  • 動態路由:
    • url中路由是改變的,可是改變路由公用一個組件
    • 舉例:
      • localhost:3000/detail/001?a=1&b=2
      • localhost:3000/detail/002?a=2&b=3
      • detail
  • vue cli3 配置反向代理 20分鐘
    • 在根目錄下面新建一個 vue.config.js
// vue.config.js中能夠默認直接使用  http-proxy-middleware
  module.exports = {
    devServer: {
      proxy: {
        '/douban': { // /douban 是一個標記
          target: 'http://api.douban.com', // 目標源
          changeOrigin: true, // 修改源
          pathRewrite: {
            '^/douban': '' 
          }
        },
        '/siku': {
          target: 'https://android.secoo.com',
          changeOrigin: true,
          pathRewrite: {
            '^/siku': ''
          }
        }
      }
    }
  }
  • 路由的傳參 10分鐘
<router-link :to = "{name: 'list',params: {id: xxx}, query: {xxx:xxx}}"></router-link>
  • 路由的接參

    • 咱們發現凡是使用了路由的組件,咱們統稱爲: 路由組件
    • 路由組件身上會自動添加一個 $route的數據
    id: this.$route.params.id
      query: this.$route.query.xxx
  • 編程式導航 5分鐘

    • push
      • this.$router.push('/home')
      • this.$router.push({name,params,query})
      • push能夠將咱們的操做存放到瀏覽器的歷史記錄
    • replace
      • this.$router.replace('/home')
      • this.$router.replace({name,params,query})
      • replace沒有將咱們的操做存放到瀏覽器的歷史記錄, 效果爲返回了二級
  • 業務:

    • 按鈕的返回
      • push
      • replace
      • back
      • go

路由進階部分 -- 導航守衛( 路由守衛 )

  1. 做用: --- 相似 【保安】

    • 守衛路由
        • 舉例: 攜帶數據進
        • 舉例: 事情完成才能出
  2. 導航守衛一共有三種形式

    • A: 全局導航守衛

      1. 全局前置守衛 router.beforeEach(fn)
        1. fn中有三個參數
      2. 全局的解析守衛
        1. 在 2.5.0+ 你能夠用 router.beforeResolve 註冊一個全局守衛。這和 router.beforeEach 相似,區別是在導航被確認以前,同時在全部組件內守衛和異步路由組件被解析以後,解析守衛就被調用。
        2. 必須保證整個項目的守衛和異步路由組件解析完成
      3. 全局的後置守衛
        • 能夠作一些用戶友好提示
    • B: 路由獨享守衛 beforeEnter

      • 寫在路由表中的守衛鉤子
      • 針對的是和當前路由相關的,那麼其餘與之不相關的路由,它是沒法監聽它的變化狀況的
    • C: 組件內守衛

      • 組件內的前置守衛 beforeRouteEnter((to,from,next)=>{})

        • 導航進入組件時,調用
        • this是訪問不到的,若是非要訪問this ,必須經過 next(vm=>{})訪問
        • 由於組件此時沒有建立,因此沒有this
        • 案例: 數據預載(進入組件前就得到數據)
        next(vm => { //vm指的就是組件
               const result = JSON.parse(res.data.slice(7,-1)).rp_result.categorys
               vm.$set(vm.category,'categorys',result)
             })
      • 組件內的後置守衛
        - 當好離開組件時,調用
        - this是能夠訪問到

      • 組件內的更新守衛( 路由傳參和路由的接參 )

        • 在當前路由改變,可是該組件被複用時調用
        • 舉例來講,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
        • 因爲會渲染一樣的 Foo 組件,所以組件實例會被複用。而這個鉤子就會在這個狀況下被調用。
        • 能夠訪問組件實例 this
  3. 功能: 導航守衛能夠監聽路由變化狀況

  4. 名詞

    • 前置: 要進入當前路由 --- 老師進入教室前
    • 後置: 要離開當前路由 --- 老師離開教室
  5. 關於next的使用

    • next() 等價於 next( true ) 表示能夠從當前路由跳轉到目標路由
    • next( false ) 表示不經過, 表示從當前路由跳轉不到目標路由
    • next('/login') 等價於 next({path:'/login'}) 跳轉指定的路由
    • next('/login') 等價於 next({path:'/login',params,query})
    • next( fn ) 數據預載
  6. 業務: 當咱們進入到一個項目的首頁時,可是當咱們沒有註冊帳號時,它主動跳轉到了註冊/登陸頁

router.beforeEach((to,from,next)=>{
      const name = localStorage.getItem('name')
      if( name || to.path === '/login' ){
        //若是有   /  -->  /home
        next()
      }else{
        next('/login')
      }
  })
  1. 業務: 當進入mine頁面的時候, 要判斷用戶是否登陸,若是沒有登陸,跳轉登陸頁
  2. 路由導航守衛
    • 3中類型 7個路由監聽鉤子
  • 業務:
    • 監聽整個項目的路由變化狀況 全局的前置守衛
    • 監聽某個路由的變化狀況 路由的獨享守衛
    • 監聽的路由組件的路由變化狀況 組件內的導航守衛
  1. 動效
  2. 路由懶加載
    1. Vue異步組件 + Webpack
相關文章
相關標籤/搜索