---
date: 2022-09-06
title: VuePress 魔改 Nprogress 进度条为胶囊状
category: experience
cover: /images/631f1ecef211d.webp
recommend: true
original: true
location: 甘肃
tags:

- VuePress
- Nprogress

---

### 前言

这个样式是逛 `张洪Heo` 博客的时候看见的，感觉这种方式也非常的好看所以就抄了下来，因为 `@vuepress/plugin-nprogress`
这个插件并不能自定义 `Nprogress` 的配置，所以我们直接引用原生的 `Nprogress` 来操作。

### 实现效果

![Nprogress 进度条魔改](/images/631f3e09364f5.webp)

### 实现代码

```js
// .vuepress/enhanceApp.js
export default ({Vue, options, router, siteData, isServer}) => {
    Vue.mixin({
        mounted() {
            // nprogress 魔改 start
            import('nprogress').then((nprogress) => {
                nprogress.configure({
                    showSpinner: false,
                    template: '<div class="bar"><div class="peg" role="bar"></div></div></div>',
                    speed: 500
                })
                router.beforeEach((to, from, next) => {
                    if (to.path !== from.path) {
                        nprogress.start()
                    }
                    next()
                })
                router.afterEach(() => {
                    nprogress.done()
                })
            })
            // nprogress 魔改 end
        }
    })
};
```

```stylus
// .vuepress/theme/styles/index.style
@keyframes gradient {
  0% {
    background-position: 0 50%
  }
  50% {
    background-position: 100% 50%
  }
  100% {
    background-position: 0 50%
  }
}

#nprogress {
  .bar {
    position: fixed;
    left: 50%;
    width: 80px;
    background: transparent;
    transform: translateX(-50%);
    height: 6px;
    margin: 0 auto;
    top: 6px;
    overflow: hidden;
    border-radius: 3px;
    border: 1px solid #42444a;

    .peg {
      width: 100px;
      background: linear-gradient(215deg, #4584ff 0%, #cf0db9 100%);
      background-size: 200%;
      box-shadow: none;
      animation: gradient 2s ease infinite;
    }
  }
}
```