如何在 Vue.js 应用程序中添加加载指示器

简介

加载指示器改善了任何应用程序中的UX(用户体验)-网络或移动。这些动画向用户提供正在执行的操作的反馈,结果将很快返回。

在Web应用程序中,有两个主要事件需要加载器:

  • 网络请求,如导航到不同的页面或AJAX请求。
  • 当运行繁重的计算时。

本文将介绍几种将加载器添加到Vue.js应用程序的方法。

前提条件

要完成本教程,您需要:

本教程已在Node v14.2.0、npm v6.14.5、vue v2.6.11和vue-router v3.1.6中验证。

第一步-设置项目

让我们创建一个新的Vue项目。本教程将使用Vue CLI(命令行界面)来构建您的应用程序:

1npx @vue/cli@4.5.4 create --inlinePreset='{ "useConfigFiles": false, "plugins": { "@vue/cli-plugin-babel": {}, "@vue/cli-plugin-eslint": { "config": "base", "lintOn": ["save"] } }, "vuex": true, "router": true, "routerHistoryMode": true }' vue-loading-indicators

这个长命令是一组基于@vue/cli/Packages/@vue/cli/lib/options.js默认设置的预设值。当重新格式化以提高可读性时,它看起来如下所示:

 1{
 2  "useConfigFiles": false,
 3  "plugins": {
 4    "@vue/cli-plugin-babel": {},
 5    "@vue/cli-plugin-eslint": {
 6      "config": "base",
 7      "lintOn": ["save"]
 8    }
 9  },
10  "vuex": true,
11  "router": true,
12  "routerHistoryMode": true
13}

这些预置添加vue-router作为插件(cli-plugin-router),,添加vuex作为插件(cli-plugin-vuex),ENABLE_HISTORY MODE_,添加babel,添加eSLint。

为了满足本教程的需要,您将不需要TypesScrip、渐进式Web应用程序(PWA)支持、Vuex、CSS预处理器、单元测试或端到端(E2E)测试。

接下来,切换到新的项目目录:

1cd vue-loading-indicators

您可以通过运行以下命令在Web浏览器中查看您的应用程序:

1npm run serve

当您在Web浏览器中访问localhost:8080时,您应该会看到一条欢迎使用您的Vue.js应用程序消息。由于您包含了Vue Router,因此还将提供指向 Home 页面和** About** 页面的链接。您的目标是在这两个页面之间导航时添加一个加载指示器。

如果您想了解更多关于Vue CLI的信息,可以参考Vue CLI文档.

现在,您可以开始构建了。

Step 2-使用nProgress s

您可以使用您选择的任何加载指示器。在本教程中,您将安装nprogress以用作加载指示器。

为此,您不会使用npmya n。您将从CDN(内容交付网络)引用它。

在创建的Vue CLI工程中,导航到public/index.html文件:

1nano public/index.html

并在结束</head>标签前添加下面的代码片段:

1[label public/index.html]
2<head>
3  <!-- ... -->
4  <link href="https://unpkg.com/[email protected]/nprogress.css" rel="stylesheet" />
5  <script src="https://unpkg.com/[email protected]/nprogress.js"></script>
6</head>

nProgress公开了一个几个接口方法,,但在本文中,您需要两个方法--startdoned。这些方法启动和停止进度条。

nprogress也可以配置为如何推进加载器。虽然可以手动定制,但本文将使用默认行为。

步骤3 -使用路由器

当您使用路由器向您的网站添加进度条时,您期望的典型功能是:

当用户导航到新页面时,加载程序开始在页面顶部打勾,向用户显示下一页的下载进度。

动画gif,描绘screen.顶部的加载进度条

VueRouter带有可以挂钩的钩子,使您可以实现这一功能。

打开src/router/index.js文件:

1nano src/router/index.js

并在export前添加如下代码:

 1[label src/router/index.js]
 2// ...
 3
 4router.beforeResolve((to, from, next) => {
 5  // If this isn't an initial page load.
 6  if (to.name) {
 7    // Start the route progress bar.
 8    NProgress.start()
 9  }
10  next()
11})
12
13router.afterEach((to, from) => {
14  // Complete the animation of the route progress bar.
15  NProgress.done()
16})
17
18export default router

当您连接到bepreResolve路由时,您就是在告诉路由器在页面请求发生后启动nProgress‘。After Each`挂钩告诉路由器,在链接完成评估以停止进度条之后,它不应该关心页面请求是否成功。

此时,您可以运行您的应用程序:

1npm run serve

当您在Web浏览器中访问localhost:8080时,您可以在 Home 页面和** About** 页面之间导航。当您这样做时,您将看到添加到应用程序中的加载指示器。

下一步将进一步探索加载指标。

第四步-探索高级用法

在本节中,将向您介绍在应用程序中加载指示器的其他用例。

这些将与示例一起呈现,除非您想要自己探索,否则您不会在教程中直接实现它们。

使用HTTP库

您可能希望为应用程序添加进度条的另一个部分是当您的用户发出AJAX请求时。

如今,大多数HTTP库都有一种在请求或响应发生之前触发的中间件或拦截器。正因为如此,您还可以连接到您选择的库中。

在本教程中,您将使用axios.这个库使用术语拦截器。

安装axios

1npm install [email protected]

然后创建一个HTTP.js文件:

1nano HTTP.js

然后,您可以这样配置axios

 1[label HTTP.js]
 2import axios from 'axios'
 3
 4// create a new axios instance
 5const instance = axios.create({
 6  baseURL: '/api'
 7})
 8
 9// before a request is made start the nprogress
10instance.interceptors.request.use(config => {
11  NProgress.start()
12  return config
13})
14
15// before a response is returned stop nprogress
16instance.interceptors.response.use(response => {
17  NProgress.done()
18  return response
19})
20
21export default instance

这段代码允许您处理连接,并在每次发出请求时获得一个进度条。

在组件内使用Loaders

有时,您不是在发出页面请求或AJAX请求。这可能只是一个依赖于浏览器的操作,需要时间。

让我们考虑一个自定义的DownloadButton组件,它可以因为一些外部操作而将其状态更改为正在加载状态。

组件将只带一个道具Loading

1<template>
2  <DownloadButton :loading="loading">Download</DownloadButton>
3</template>

该示例组件如下所示:

<$>[备注] 注意: 本例中没有定义SVGviewBoxpathstyle的一些更精细的细节。 <$>

 1[label src/components/DownloadButton.vue]
 2<template>
 3  <button class="Button" :disabled="loading">
 4    <svg v-if="loading" class="Button__Icon Button__Spinner" viewBox="...">
 5      <path d="..."/>
 6    </svg>
 7    <svg v-else class="Button__Icon" viewBox="0 0 20 20">
 8      <path d="..."/>
 9    </svg>
10    <span v-if="!loading" class="Button__Content">
11      <slot/>
12    </span>
13  </button>
14</template>
15
16<script>
17export default {
18  props: {
19    loading: { type: Boolean }
20  }
21}
22</script>
23
24<style>
25  /* ... */
26</style>

以下是此代码将产生的结果的演示:

用户与下载按钮和加载圈appearing.交互的动画gif

使用高阶组件实现可重用的加载器

您可以为我们的组件创建作为包装器(HOC)的加载器,然后可以通过道具修改它们的状态。

这些类型的加载器适用于不影响应用程序全局状态的组件,但您仍然希望用户感觉与适当的操作相关联。

下面是一个例子:

<$>[备注] 注意: 本例中没有定义Stats内容的一些更细微的细节。 <$>

 1// This loader will add an overlay with the text of 'Loading...'
 2const Loader = {
 3  template: `
 4    <div class="{'is-loading': loading}">
 5      <slot/>
 6    </div>
 7  `,
 8  props: ['loading']
 9}
10
11const Stats = {
12  template: `
13    <Loader :loading="updating">
14      ...
15    </Loader>
16  `,
17  props: ['updating']
18}
19
20const app = new Vue({
21  template: `
22    <div class="widget">
23      <Stats :updating="fetchingStats"/>
24      <Button @click="fetchingStats = true">
25        Latest stats
26      </Button>
27    </div>
28  `,
29})

以下是此代码将产生的结果的演示:

带有更新按钮的框,用户单击更新,框呈灰色显示正在加载的message

使用异步Vue组件

Vue的asynchronous components允许您仅在需要时从服务器获取组件。最终用户只需要他们需要的东西,而不是他们可能永远不会使用的组件。

异步组件还自带了对加载和错误states,]的本地支持,因此这里不需要任何额外的配置。

下面是一个例子:

 1const AsyncComponent = () => ({
 2  component: import('./MyComponent.vue'),
 3  // show this component during load
 4  loading: LoadingComponent,
 5  // show this component if it fails to load
 6  error: ErrorComponent,
 7  // delay before showing the loading component
 8  delay: 200,
 9  // error if the component failed to loadin is allotted time in milliseconds default in Infinity
10  timeout: 3000
11})

要在这里的方法中使用Apache组件,您需要使用Vue Router lazy loading

总结

在本文中,您探索了将加载指示器添加到Vue.js应用程序的一些方法。加载指示器是向用户提供反馈的有用工具。

如果您想了解更多关于Vue.js的信息,请查看我们的Vue.js主题页面获取练习和编程项目。

Published At
Categories with 技术
comments powered by Disqus