久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長(zhǎng)資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      深入了解Vue的中間件管道(middleware pipeline)

      深入了解Vue的中間件管道(middleware pipeline)

      通常,在構(gòu)建SPA時(shí),需要保護(hù)某些路由。例如假設(shè)有一個(gè)只允許經(jīng)過(guò)身份驗(yàn)證的用戶訪問(wèn)的 dashboard 路由,我們可以通過(guò)使用 auth 中間件來(lái)確保合法用戶才能訪問(wèn)它。

      在本教程中,我們將學(xué)到怎樣用 Vue-Router 為Vue應(yīng)用程序?qū)崿F(xiàn)中間件管道。

      什么是中間件管道?

      中間件管道(middleware pipeline)是一堆彼此并行運(yùn)行的不同的中間件。

      繼續(xù)前面的案例,假設(shè)在 /dashboard/movies 上有另一個(gè)路由,我們只希望訂閱用戶可以訪問(wèn)。我們已經(jīng)知道要訪問(wèn) dashboard 路由,你需要進(jìn)行身份驗(yàn)證。那么應(yīng)該怎樣保護(hù) /dashboard/movies 路由以確保只有經(jīng)過(guò)身份驗(yàn)證和訂閱的用戶才能訪問(wèn)呢?通過(guò)使用中間件管道,可以將多個(gè)中間件鏈接在一起并確保它們能夠并行運(yùn)行。

      開(kāi)始

      首先用 Vue CLI 快速構(gòu)建一個(gè)新的 Vue 項(xiàng)目。

      vue create vue-middleware-pipeline

      安裝依賴(lài)項(xiàng)

      創(chuàng)建并安裝項(xiàng)目目錄后,切換到新創(chuàng)建的目錄并從終端運(yùn)行以下命令:

      npm i vue-router vuex

      Vue-router — 是Vue.js的官方路由器

      Vuex — 是 Vue 的狀態(tài)管理庫(kù)

      創(chuàng)建組件

      我們的程序?qū)齻€(gè)組件。

      Login?—?此組件展示給尚未通過(guò)身份驗(yàn)證的用戶。

      Dashboard?— 此組件展示給已登錄的用戶。

      Movies?—?我們會(huì)向已登錄并擁有有效訂閱的用戶顯示此組件。

      讓我們創(chuàng)建這些組件。切換到 src/components 目錄并創(chuàng)建以下文件:Dashboard.vueLogin.vueMovies.vue

      使用以下代碼編輯 Login.vue 文件:

      <template>   <p>     <p>This is the Login component</p>   </p> </template>

      使用以下代碼編輯 Dashboard.vue 文件:

      <template>   <p>     <p>This is the Dashboard component for authenticated users</p>     <router-view/>   </p> </template>

      最后,將以下代碼添加到 Movies.vue 文件中:

      <template>   <p>     <p>This is the Movies component for authenticated and subscribed users</p>   </p> </template>

      創(chuàng)建store

      Vuex 而言,store 只是一個(gè)用于保存我們程序狀態(tài)的容器。它允許我們確定用戶是否經(jīng)過(guò)身份驗(yàn)證以及檢查用戶是否已訂閱。

      在 src 文件夾中,創(chuàng)建一個(gè) store.js 文件并將以下代碼添加到該文件中:

      import Vue from 'vue' import Vuex from 'vuex'  Vue.use(Vuex)  export default new Vuex.Store({     state: {         user: {             loggedIn: false,             isSubscribed: false         }     },     getters: {         auth(state) {             return state.user         }     } })

      store 在其 狀態(tài) 內(nèi)包含一個(gè) user 對(duì)象。 user 對(duì)象包含 loggedInisSubscribed 屬性,它可以幫助我們確定用戶是否已登錄并具有有效訂閱。我們還在 store 中定義了一個(gè) getter 來(lái)返回 user 對(duì)象。

      定義路由

      在創(chuàng)建路由之前,應(yīng)該先定義它們,并關(guān)聯(lián)將要附加到其上的對(duì)應(yīng)的中間件。

      除了通過(guò)身份驗(yàn)證的用戶之外,每個(gè)人都可以訪問(wèn) /login。當(dāng)通過(guò)身份驗(yàn)證的用戶訪問(wèn)此路由時(shí),應(yīng)重定向到 dashboard 路由。這條路由應(yīng)該附有一個(gè) guest 中間件。

      只有通過(guò)身份驗(yàn)證的用戶才能訪問(wèn) /dashboard。否則用戶在訪問(wèn)此路由時(shí)應(yīng)重定向到 /login 路由。我們把 auth 中間件與此路由相關(guān)聯(lián)。

      只有通過(guò)身份驗(yàn)并訂閱的用戶才能訪問(wèn) /dashboard/movies。該路由受到 isSubscribedauth 中間件的保護(hù)。

      創(chuàng)建路由

      接下來(lái),在 src 目錄中創(chuàng)建一 個(gè)router 文件夾,然后在該文件夾中創(chuàng)建一個(gè) router.js 文件。使用以下代碼編輯文件:

      import Vue from 'vue' import Router from 'vue-router' import store from '../store'  import Login from '../components/Login' import Dashboard from '../components/Dashboard' import Movies from '../components/Movies'   Vue.use(Router)  const router = new Router({     mode: 'history',     base: process.env.BASE_URL,     routes: [         {             path: '/login',             name: 'login',             component: Login         },          {             path: '/dashboard',             name: 'dashboard',             component: Dashboard,             children: [{                 path: '/dashboard/movies',                 name: 'dashboard.movies',                 component: Movies             }         ],         }     ] })   export default router

      在這里,我們創(chuàng)建了一個(gè)新的 router 實(shí)例,同時(shí)傳遞了幾個(gè)配置選項(xiàng)以及一個(gè) routes 屬性,它接受我們之前定義的所有路由。要注意目前這些路由還都是不受保護(hù)的。我們很快就會(huì)解決這個(gè)問(wèn)題。

      接下來(lái)將路由和 store 注入Vue 實(shí)例。使用以下代碼編輯 src/main.js 文件:

      import Vue from 'vue' import App from './App.vue' import router from './router/router' import store from './store'  Vue.config.productionTip = false   new Vue({   router,   store,   render: h => h(App), }).$mount('#app')

      創(chuàng)建中間件

      src/router 目錄中創(chuàng)建一個(gè) middleware 文件夾,然后在該文件夾下創(chuàng)建 guest.js,auth.jsIsSubscribed.js文件。將以下代碼添加到 guest.js 文件中:

      export default function guest ({ next, store }){     if(store.getters.auth.loggedIn){         return next({            name: 'dashboard'         })     }         return next()    }

      guest 中間件檢查用戶是否通過(guò)了身份驗(yàn)證。如果通過(guò)了身份驗(yàn)證就會(huì)被重定向到 dashboard 路徑。

      接下來(lái),用以下代碼編輯 auth.js 文件:

      export default function auth ({ next, store }){  if(!store.getters.auth.loggedIn){      return next({         name: 'login'      })  }   return next() }

      auth 中間件中,我們用 store 檢查用戶當(dāng)前是否已經(jīng) authenticated。根據(jù)用戶是否已經(jīng)登錄,我們要么繼續(xù)請(qǐng)求,要么將其重定向到登錄頁(yè)面。

      使用以下代碼編輯 isSubscribed.js 文件:

      export default function isSubscribed ({ next, store }){     if(!store.getters.auth.isSubscribed){         return next({            name: 'dashboard'         })     }         return next()    }

      isSubscribed 中的中間件類(lèi)似于 auth 中間件。我們用 store檢查用戶是否訂閱。如果用戶已訂閱,那么他們可以訪問(wèn)預(yù)期路由,否則將其重定向回 dashboard 頁(yè)面。

      保護(hù)路由

      現(xiàn)在已經(jīng)創(chuàng)建了所有中間件,讓我們利用它們來(lái)保護(hù)路由。使用以下代碼編輯 src/router/router.js 文件:

      import Vue from 'vue' import Router from 'vue-router' import store from '../store'  import Login from '../components/Login' import Dashboard from '../components/Dashboard' import Movies from '../components/Movies'  import guest from './middleware/guest' import auth from './middleware/auth' import isSubscribed from './middleware/isSubscribed'  Vue.use(Router)  const router = new Router({     mode: 'history',     base: process.env.BASE_URL,     routes: [{             path: '/login',             name: 'login',             component: Login,             meta: {                 middleware: [                     guest                 ]             }         },         {             path: '/dashboard',             name: 'dashboard',             component: Dashboard,             meta: {                 middleware: [                     auth                 ]             },             children: [{                 path: '/dashboard/movies',                 name: 'dashboard.movies',                 component: Movies,                 meta: {                     middleware: [                         auth,                         isSubscribed                     ]                 }             }],         }     ] })  export default router

      在這里,我們導(dǎo)入了所有中間件,然后為每個(gè)路由定義了一個(gè)包含中間件數(shù)組的元字段。中間件數(shù)組包含我們希望與特定路由關(guān)聯(lián)的所有中間件。

      Vue 路由導(dǎo)航守衛(wèi)

      我們使用 Vue Router 提供的導(dǎo)航守衛(wèi)來(lái)保護(hù)路由。這些導(dǎo)航守衛(wèi)主要通過(guò)重定向或取消路由的方式來(lái)保護(hù)路由。

      其中一個(gè)守衛(wèi)是全局守衛(wèi),它通常是在觸發(fā)路線之前調(diào)用的鉤子。要注冊(cè)一個(gè)全局的前衛(wèi),需要在 router 實(shí)例上定義一個(gè) beforeEach 方法。

      const router = new Router({ ... }) router.beforeEach((to, from, next) => {  //necessary logic to resolve the hook })

      beforeEach 方法接收三個(gè)參數(shù):

      to: 這是我們打算訪問(wèn)的路由。

      from: 這是我們目前的路由。

      next: 這是調(diào)用鉤子的 function。

      運(yùn)行中間件

      使用 beforeEach 鉤子可以運(yùn)行我們的中間件。

      const router = new Router({ ...})  router.beforeEach((to, from, next) => {     if (!to.meta.middleware) {         return next()     }     const middleware = to.meta.middleware      const context = {         to,         from,         next,         store     }     return middleware[0]({         ...context     }) })

      我們首先檢查當(dāng)前正在處理的路由是否有一個(gè)包含 middleware 屬性的元字段。如果找到 middleware 屬性,就將它分配給 const 變量。接下來(lái)定義一個(gè) context 對(duì)象,其中包含我們需要傳遞給每個(gè)中間件的所有內(nèi)容。然后,把中間件數(shù)組中的第一個(gè)中間件做為函數(shù)去調(diào)用,同時(shí)傳入 context 對(duì)象。

      嘗試訪問(wèn) /dashboard 路由,你應(yīng)該被重定向到 login 路由。這是因?yàn)?/src/store.js 中的 store.state.user.loggedIn 屬性被設(shè)置為 false。將 store.state.user.loggedIn 屬性改為 true,就應(yīng)該能夠訪問(wèn) /dashboard 路由。

      現(xiàn)在中間件正在運(yùn)行,但這并不是我們想要的方式。我們的目標(biāo)是實(shí)現(xiàn)一個(gè)管道,可以針對(duì)特定路徑運(yùn)行多個(gè)中間件。

      return middleware[0]({ …context})

      注意上面代碼塊中的這行代碼,我們只調(diào)用從 meta 字段中的中間件數(shù)組傳遞的第一個(gè)中間件。那么我們?cè)鯓哟_保數(shù)組中包含的其他中間件(如果有的話)也被調(diào)用呢?這就是管道派上用場(chǎng)的地方。

      創(chuàng)建管道

      切換到 src/router 目錄,然后創(chuàng)建一個(gè) middlewarePipeline.js 文件。將以下代碼添加到文件中:

      function middlewarePipeline (context, middleware, index) {     const nextMiddleware = middleware[index]      if(!nextMiddleware){         return context.next      }      return () => {         const nextPipeline = middlewarePipeline(             context, middleware, index + 1         )          nextMiddleware({ ...context, next: nextPipeline })      } }  export default middlewarePipeline

      middlewarePipeline 有三個(gè)參數(shù):

      context: 這是我們之前創(chuàng)建的 context 對(duì)象,它可以傳遞給棧中的每個(gè)中間件。

      middleware: 這是在 routemeta 字段上定義的middleware 數(shù)組本身。

      index: 這是在 middleware 數(shù)組中運(yùn)行的當(dāng)前中間件的 index。

      const nextMiddleware = middleware[index] if(!nextMiddleware){ return context.next }

      在這里,我們只是在傳遞給 middlewarePipeline 函數(shù)的 index 中拔出中間件。如果在 index 沒(méi)有找到 middleware,則返回默認(rèn)的 next 回調(diào)。

      return () => { const nextPipeline = middlewarePipeline( context, middleware, index + 1 ) nextMiddleware({ ...context, next: nextPipeline }) }

      我們調(diào)用 nextMiddleware 來(lái)傳遞 context, 然后傳遞 nextPipeline const。值得注意的是,middlewarePipeline 函數(shù)是一個(gè)遞歸函數(shù),它將調(diào)用自身來(lái)獲取下一個(gè)在堆棧中運(yùn)行的中間件,同時(shí)將index增加為1。

      把它們放在一起

      讓我們使用middlewarePipeline。像下面這段代碼一樣編輯 src/router/router.js 文件:

      import Vue from 'vue' import Router from 'vue-router' import store from '../store'  import Login from '../components/Login' import Dashboard from '../components/Dashboard' import Movies from '../components/Movies'  import guest from './middleware/guest' import auth from './middleware/auth' import isSubscribed from './middleware/isSubscribed' import middlewarePipeline from './middlewarePipeline'  Vue.use(Router)  const router = new Router({     mode: 'history',     base: process.env.BASE_URL,     routes: [{             path: '/login',             name: 'login',             component: Login,             meta: {                 middleware: [                     guest                 ]             }         },         {             path: '/dashboard',             name: 'dashboard',             component: Dashboard,             meta: {                 middleware: [                     auth                 ]             },             children: [{                 path: '/dashboard/movies',                 name: 'dashboard.movies',                 component: Movies,                 meta: {                     middleware: [                         auth,                         isSubscribed                     ]                 }             }],         }     ] })  router.beforeEach((to, from, next) => {     if (!to.meta.middleware) {         return next()     }     const middleware = to.meta.middleware     const context = {         to,         from,         next,         store     }      return middleware[0]({         ...context,         next: middlewarePipeline(context, middleware, 1)     }) })  export default router

      在這里,我們使用 <code> middlewarePipeline <code>來(lái)運(yùn)行棧中包含的后續(xù)中間件。

      return middleware[0]({ ...context, next: middlewarePipeline(context, middleware, 1) })

      在調(diào)用第一個(gè)中間件之后,使用 middlewarePipeline 函數(shù),還會(huì)調(diào)用棧中包含的后續(xù)中間件,直到不再有中間件可用。

      如果你訪問(wèn) /dashboard/movies 路由,應(yīng)該被重定向到 /dashboard。這是因?yàn)?user 當(dāng)前是 authenticated 但沒(méi)有有效訂閱。如果將 store 中的 store.state.user.isSubscribed 屬性設(shè)置為 true,就應(yīng)該可以訪問(wèn) /dashboard/movies 路由了。

      結(jié)論

      中間件是保護(hù)應(yīng)用中不同路由的好方法。這是一個(gè)非常簡(jiǎn)單的實(shí)現(xiàn),可以使用多個(gè)中間件來(lái)保護(hù) Vue 應(yīng)用中的單個(gè)路由。你可以在(https://github.com/Dotunj/vue-middleware-pipelines)找到所有的源碼。

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)