溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue進度條組件怎么弄

發(fā)布時間:2020-10-19 14:48:44 來源:億速云 閱讀:216 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了Vue進度條組件怎么弄,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

最近在個人的項目中,想對頁面之間跳轉的過程進行優(yōu)化,想到了很多文檔或 npm 等都用到的頁面跳轉進度條,于是便想自己去實現(xiàn)一個,特此記錄。

來看下 npm 搜索組件時候的效果:

Vue進度條組件怎么弄

so 下面咱們一起動手實現(xiàn)一下唄。

定義使用方式

想實現(xiàn)一個組件的前提,一定要想好你的需求是什么,還要自己去定義一個舒服的使用方法,這其中也是有原則的,對使用者來說,使用方式越簡單越好。那么對應的代價就是寫這個組件的復雜度會變高。

我想要的使用方式是這樣的:可以在任意的地方去調(diào)用到這個方法,可以隨時控制其狀態(tài)。

看下對應的代碼:

async someFunction () {
    this.$progress.start()
    try {
          const ret = await axios.get('/xxx')
          // some code ...
      this.$progress.finish()
    } catch (err) {
          // cache err ...
          this.$progress.fail()
    }
}

當然,想在任意地方使用,少不了一個步驟,就是在全局注冊這個組件:

import progressBar from 'xxx/progress-bar'

Vue.use(progressBar, { // some config ... })

如果不想全局注冊,你也可以在某個組件內(nèi)單獨使用,只要你開心就好。

實現(xiàn)過程

先來建立一個文件夾和其中兩個文件:

progress-bar
    - 01 progress-bar.vue
    - 02 index.js

打開progress-bar.vue,先來寫結構和樣式,這里很簡單:

<template>
      <p :style='style'></p>
</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>

除了要定義的屬性以外,那么組件本身總要有一些自己的屬性,用來控制自己的狀態(tài),比如這個組件,你要控制進度條的長度、顯示和隱藏等狀態(tài)。

添加 vue 的 data 屬性:

data () {
      return {
      percent: 0,  // 進度條長度
            show: false, // 顯示和隱藏
            canSuccess: true  // 是否是成功的狀態(tài)
      }
}

有了這些屬性,這個進度條就要根據(jù)這些屬性的變化來“自己動”。所以這個時候首先想到的當然就是 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 狀態(tài),你可以可以設置讓其永遠不完成動畫的動作。

第二步,來寫一個對象,其中包含 start 、 finish 、 fail 方法以及動畫代碼。

第三步,將這個對象掛在到 Vue 的原型

完整的代碼和說明如下:

import progressBar from './progress-bar.vue'

export default {
  install (Vue, options = {}) {
    // 注冊組件
    Vue.component(progressBar.name, progressBar)

    // 創(chuàng)建一個 Vue 子類
    const Component = Vue.extend(progressBar)
    // 拿到自定義的屬性
    const { autoFinish, ...res } = options
    // 創(chuàng)建組件實例
    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()

    // 如果是服務端渲染那么不繼續(xù)執(zhí)行
    if (!vm.$isServer) {
      document.body.appendChild(vm.$el)
    }

    let timer = null

    const progress = {
      start () {
        if (Vue.$isServer) return

        // 每次調(diào)用 start 都重新初始化一次,比如多次點擊某個按鈕連續(xù)請求,那么每次都從0開始
        vm.percent = 0
        vm.show = true
        vm.canSuccess = true

        // 定一個增量,這個值可以改成參數(shù),也可以按照使用經(jīng)驗來設定
        const CUT_SCALE = 5

        // 定義每 100 秒來執(zhí)行一次動畫
        timer = setInterval(() => {
          // 每次執(zhí)行增量動畫
          this.increase((CUT_SCALE - 1) * Math.random() + 1)
          // 如果進度大于 95%,并且設置了自動完成,那么執(zhí)行結束動作
          if (vm.percent > 95 && vm.autoFinish) {
            this.finish()
          }
        }, 100)
      },

      increase (cut) {
        vm.percent = Math.min(99, vm.percent + cut)
      },

      hide () {
        clearInterval(timer)
        // 這里面有2個定時器,外層定時器是讓用戶可以看到這個 進度已經(jīng)完成啦
        // 內(nèi)層定時器,由于 opacity 消失需要一定的過渡時間,所以要等待它消失以后
        // 在將其進度設置為0,等待下次調(diào)用,如果不延遲,那么會看到進度到100后又回到0的動畫
        setTimeout(() => {
          vm.show = false
          setTimeout(() => {
            vm.percent = 0
            timer = null
          }, vm.options.transition.opacitySpeed)
        }, vm.options.transition.duration)
      },

      // 下面這2個方法就很簡單了,只需要完成進度,然后執(zhí)行隱藏即可
      finish () {
        if (Vue.$isServer) return
        vm.percent = 100
        this.hide()
      },

      fail () {
        if (Vue.$isServer) return
        // 修改未成功的狀態(tài),實際效果就是改變最后的顏色
        vm.canSuccess = false
        vm.percent = 100
        this.hide()
      }
    }

    // 最后掛在到全局
    Vue.prototype.$progress = progress
  }
}

感謝你能夠認真閱讀完這篇文章,希望小編分享Vue進度條組件怎么弄內(nèi)容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI