在Vue中使用NProgress监控页面滚动进度

NProgress是用来在页面跳转时出现在浏览器顶部的进度条
官网:http://ricostacruz.com/nprogress/
github: https://github.com/rstacruz/nprogress

博主想用Vue实现全局监控页面滚动条的进度。功能与NProgress相似,因此直接使用当前插件来进行实现。

效果:
在这里插入图片描述

一、安装

npm install --save nprogress

yarn add nprogress

二、使用

1. 作为加载进度条

在Vue入口文件 main.js 中引入 nprogress

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' //引入 nprogress 插件
import 'nprogress/nprogress.css' // 引入基础样式

切换路由时进行加载(也是在main.js中)

//当路由进入前
router.beforeEach((to, from, next) => {
  // 每次切换页面时,调用进度条
  NProgress.start();
  // 这个一定要加,没有next()页面不会跳转的。这部分还不清楚的去翻一下官网就明白了
  next();
});
//当路由进入后:关闭进度条
router.afterEach(() => {
  // 在即将进入新的页面组件前,关闭掉进度条
  NProgress.done()
})

2. 作为页面滚动进度条

在 App.vue 中

<script>
import NProgress from "nprogress"; // 导入nprogress(因为在main.js 中已经导入样式,这里不需要再次导入)
export default {
  name: "App",
  mounted() {
    window.addEventListener("scroll", this.handleScroll); // 监听滚动条事件
  },
  methods: {
    handleScroll() {
      // 屏幕剩余的高度
      let surplus =
        document.documentElement.scrollHeight -
        document.documentElement.clientHeight;
      // 当前滑动高度
      let scrollY = document.documentElement.scrollTop;
      // 当前位置百分比小数
      let coorY = scrollY / surplus;
      // 设置导航栏,这里使用NProgress.set() 动态更改进度条
     NProgress.set(coorY);
    }
  }
};
</script>

三、配置项

1. 更改默认样式:

在 App.vue 中

<style>
#nprogress .bar{ //自定义进度条颜色
  background: orange !important; 
}
#nprogress .peg { // 自定义辅助阴影颜色,这里默认为透明
  box-shadow: 0 0 10px #00000000, 0 0 5px #00000000 !important; 
}
</style>
2. 配置NProgress:
  1. showSpinner:进度环显示隐藏
NProgress.configure({showSpinner: false});
  1. ease:调整动画设置,ease可传递CSS3缓冲动画字符串(如ease、linear、ease-in、ease-out、ease-in-out、cubic-bezier)。speed为动画速度(单位ms)
NProgress.configure({ease:'ease',speed:1000});
  1. minimum:设置进度条最低百分比
NProgress.configure({minimum:0.0});
  1. 百分比:通过设置progress的百分比,调用 .set(n)来控制进度,其中n的取值范围为0-1
NProgress.set(0.4);

四、参考文献

在Vue使用NProgress加载进度条
NProgress - github
vue滚动条事件(获取滚动条距离底部距离)

发布了8 篇原创文章 · 获赞 15 · 访问量 8219

猜你喜欢

转载自blog.csdn.net/qq_22241923/article/details/101211144