最近在我的的項目中,想對頁面之間跳轉的過程進行優化,想到了不少文檔或 npm 等都用到的頁面跳轉進度條,因而便想本身去實現一個,特此記錄。css
來看下 npm 搜索組件時候的效果:前端
so 下面我們一塊兒動手實現一下唄。vue
定義使用方式 ios
想實現一個組件的前提,必定要想好你的需求是什麼,還要本身去定義一個舒服的使用方法,這其中也是有原則的,對使用者來講,使用方式越簡單越好。那麼對應的代價就是寫這個組件的複雜度會變高。vue-router
我想要的使用方式是這樣的:能夠在任意的地方去調用到這個方法,能夠隨時控制其狀態。npm
看下對應的代碼:axios
async someFunction () { this.$progress.start() try { const ret = await axios.get('/xxx') // some code ... this.$progress.finish() } catch (err) { // cache err ... this.$progress.fail() } }
固然,想在任意地方使用,少不了一個步驟,就是在全局註冊這個組件:app
import progressBar from 'xxx/progress-bar' Vue.use(progressBar, { // some config ... })
若是不想全局註冊,你也能夠在某個組件內單獨使用,只要你開心就好。dom
實現過程 異步
先來創建一個文件夾和其中兩個文件:
progress-bar - 01 progress-bar.vue - 02 index.js
打開progress-bar.vue,先來寫結構和樣式,這裏很簡單:
<template> <div :style='style'></div> </template> <style scoped> .bar { position: fixed; z-index: 99999; opacity: 1; } </style>
在註冊組件的時候,我想能夠自定義一些功能,好比
固然只要你想到的均可以添加,那麼這些能夠定製的屬性,天然而然就成爲了組件的 props:
export default { name: 'progressBar', props: { options: { type: Object, default () { return { succColor: 'rgb(76, 164, 214)', failColor: 'rgb(218, 26, 101)', position: 'top', transition: { widthSpeed: 200, opacitySpeed: 400, duration: 300 // 定義消失時間 ms }, inverse: false, // 進度條的加載方向 thickness: 2 // 進度條的高度 } } } } } </script>
除了要定義的屬性之外,那麼組件自己總要有一些本身的屬性,用來控制本身的狀態,好比這個組件,你要控制進度條的長度、顯示和隱藏等狀態。
添加 vue 的 data 屬性:
data () { return { percent: 0, // 進度條長度 show: false, // 顯示和隱藏 canSuccess: true // 是不是成功的狀態 } }
有了這些屬性,這個進度條就要根據這些屬性的變化來「本身動」。因此這個時候首先想到的固然就是 Vue 的計算屬性:
computed: { style () { // 先拿到亂七八糟的屬性 const { succColor, failColor, location, transition, inverse, thickness } = this.options const { widthSpeed, opacitySpeed } = transition const { canSuccess, preset, show } = this // 定義 css 樣式 const style = { backgroundColor: canSuccess ? succColor : failColor, opacity: show ? 1 : 0 } if (position !== 'top' || position !== 'bottom') { throw new Error('The wrong config of position!') } style[position] = 0 if (inverse) { style.left = 0 } else { style.right = 0 } style.width = preset + '%' // 設置進度條長度 style.height = thickness + 'px' // 設置顯示高度 style.transition = `width ${widthSpeed}ms, opacity ${opacitySpeed}ms` // 設置過分樣式 return style } }
到這裏這個 vue 組件其實就完成了,接下來就是如何去控制它。打開index.js,先來寫一個標準的組件格式:
import progressBar from './progress-bar.vue' export default { install (Vue, options = {}) { // 註冊組件 Vue.component(progressBar.name, progressBar) } }
以後我們要用到 Vue 提供的擴展方法,來完成我們的需求。
第一步,添加 autoFinish 屬性,用來設定動畫是否能夠自動完成,默認是 true,固然若是某個路由或請求一直處於 pending 狀態,你能夠能夠設置讓其永遠不完成動畫的動做。
第二步,來寫一個對象,其中包含 start 、 finish 、 fail 方法以及動畫代碼。
第三步,將這個對象掛在到 Vue 的原型
完整的代碼和說明以下:
import progressBar from './progress-bar.vue' export default { install (Vue, options = {}) { // 註冊組件 Vue.component(progressBar.name, progressBar) // 建立一個 Vue 子類 const Component = Vue.extend(progressBar) // 拿到自定義的屬性 const { autoFinish, ...res } = options // 建立組件實例 const vm = new Component({ data: { autoFinish: typeof autoFinish === 'boolean' ? autoFinish : true } }) // 將 progressBar 的默認 options 與 自定義的 options 合併 options = Object.assign(vm.$props.options, { ...res }) //合併新的 props vm.$propsData = options vm.$mount() // 若是是服務端渲染那麼不繼續執行 if (!vm.$isServer) { document.body.appendChild(vm.$el) } let timer = null const progress = { start () { if (Vue.$isServer) return // 每次調用 start 都從新初始化一次,好比屢次點擊某個按鈕連續請求,那麼每次都從0開始 vm.percent = 0 vm.show = true vm.canSuccess = true // 定一個增量,這個值能夠改爲參數,也能夠按照使用經驗來設定 const CUT_SCALE = 5 // 定義每 100 秒來執行一次動畫 timer = setInterval(() => { // 每次執行增量動畫 this.increase((CUT_SCALE - 1) * Math.random() + 1) // 若是進度大於 95%,而且設置了自動完成,那麼執行結束動做 if (vm.percent > 95 && vm.autoFinish) { this.finish() } }, 100) }, increase (cut) { vm.percent = Math.min(99, vm.percent + cut) }, hide () { clearInterval(timer) // 這裏面有2個定時器,外層定時器是讓用戶能夠看到這個 進度已經完成啦 // 內層定時器,因爲 opacity 消失須要必定的過渡時間,因此要等待它消失之後 // 在將其進度設置爲0,等待下次調用,若是不延遲,那麼會看到進度到100後又回到0的動畫 setTimeout(() => { vm.show = false setTimeout(() => { vm.percent = 0 timer = null }, vm.options.transition.opacitySpeed) }, vm.options.transition.duration) }, // 下面這2個方法就很簡單了,只須要完成進度,而後執行隱藏便可 finish () { if (Vue.$isServer) return vm.percent = 100 this.hide() }, fail () { if (Vue.$isServer) return // 修改未成功的狀態,實際效果就是改變最後的顏色 vm.canSuccess = false vm.percent = 100 this.hide() } } // 最後掛在到全局 Vue.prototype.$progress = progress } }
到這裏,一個進度條組件就完成了。你們能夠本身動手實踐一下,起一個項目,使用 vue-router 的 beforeResolve 聲明週期鉤子,或者寫一個定時器模擬異步來測試一下。
以上是筆者概括總結,若有誤之處,歡迎指出。
訂閱號ID:Miaovclass
關注妙味訂閱號:「妙味前端」,爲您帶來優質前端技術乾貨;