页面交互响应进度条 NProgress 入门实践

发布时间:2024-01-18 20:14:04 浏览量:350次

一、前言

生活中,我们总是希望我们的付出,能得到对方的回应。在web交互中,也是这样的,我们总是希望我们的每一次点击,都能得到应有的响应。

页面交互响应进度条

而在当网络有延迟,web请求得不到快速回馈,我们会以为自己点击无效,多次点击使页面崩溃,面对这些情况,使用 NProgress 就能使问题得到解决。

官方体验地址:
https://ricostacruz.com/nprogress/

二、使用方法

1.安装 NProgress 到工程中:

npm install nprogress

2.导入到项目中

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

3.在响应程序前后,使用 NProgress

// 开始
NProgress.start();

// 响应程序
{...}

// 结束
NProgress.done();

三、代码演示

(1)前端

基于ElementUI的Starter来编写的,当然基于 Vue/Webpack 都可以,只不过笔者想减少无关操作,快速演示效果。

ElementUI的Starter:
https://github.com/ElementUI/element-starter

<template>
	<div id="app">
		<img src="./assets/logo.png">
		<div>
			<el-button @click="startHacking">Start</el-button>
		</div>
	</div>
</template>
<script>
	// 导入 NProgress 包对应的JS和CSS
	import NProgress from 'nprogress'
	import 'nprogress/nprogress.css'

	export default {
		methods: {
			async startHacking() {
				NProgress.start();

				const {
					data: res
				} = await this.$http.get("http://localhost/test/hello");

				this.$notify({
					title: 'OK',
					type: 'success',
					message: res,
					duration: 3000
				})

				NProgress.done();
			}
		}
	}
</script>
<style>
	#app {
		font-family: Helvetica, sans-serif;
		text-align: center;
	}
</style>

(2)后端

一个简单的基于 SpringBoot 的接口

package com.cun.nprogressserver.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/hello")
    public String hello() throws InterruptedException {
        // 模拟后端数据处理消耗的时间
        Thread.sleep(1000);
        return "hello";
    }
}

(3)效果

点击 Start 按钮,网页上方有一条响应条 ~

四、小结

NProgress 轻量易用,几行代码的引入,即可为项目增添几许别致的动感,赶紧试试吧!

本文全部代码

前端:
https://github.com/larger5/nprogress-web

后端:
https://github.com/larger5/nprogress-server

热门课程推荐

热门资讯

请绑定手机号

x

同学您好!

您已成功报名0元试学活动,老师会在第一时间与您取得联系,请保持电话畅通!
确定