如何将加载指示器添加到您的Vue.js应用程序

Loading indicators improve UX (user experience) in any application web or mobile. It tells the user that an action is being carried and a result will return shortly.

加载指示器可改善任何应用程序Web或移动设备中的UX(用户体验)。 它告诉用户正在执行一项操作,结果将很快返回。

In web applications, there are two major events that need loaders:

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

  • Network requests like navigating to a different page or an AJAX request.

    网络请求,例如导航到其他页面或AJAX请求。
  • When a heavy computation is running.

    当大量计算正在运行时。

This article will show a few ways we can add loaders to our Vue.js applications.

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

装载指示器的类型 (Types of loading indicators)

The type of loading indicator you use on your website has either a positive or negative effect on the user. Primarily, there are two types of indicators we can use on our websites.

您在网站上使用的负载指示器的类型对用户有正面或负面的影响。 首先,我们可以在网站上使用两种类型的指标。

The first is a counter. It can be in the form of a progress bar or a counter that counts from zero to hundred. This is the most effective type of loading indicator as it gives the user a rough estimate of when the action they performed will complete.

首先是柜台。 它可以采用进度条或计数器(从零到一百)的形式。 这是最有效的加载指示符类型,因为它可以使用户大致估计他们何时完成的操作。

The second is a loop. This type of loader is some sort of running animation. The most common example we see on the web is a spinner.

第二个是循环。 这种类型的加载程序是某种正在运行的动画。 我们在网络上看到的最常见的示例是微调器。

While the counter loading indicator is most suitable for long running tasks, the loop indicator is perfect for short running tasks.

计数器加载指示器最适合长时间运行的任务,而循环指示器非常适合短期运行的任务。

If you use a looping indicator for a long-running task, it builds the user’s anxiety and causes them to think that the site iss broken, their action failed, and leave with negative thoughts. Therefore for long running tasks, avoid looping indicators.

如果将循环指示器用于长时间运行的任务,则会加剧用户的焦虑,并使他们认为该站点已损坏,其操作失败并带有消极想法。 因此,对于长时间运行的任务,请避免循环显示指示器。

Either type of loading indicator is fine for short tasks even though looping indicators much better.

两种类型的加载指示器都适用于短期任务,即使循环指示器要好得多。

入门 (Getting started)

Let’s create a new project. I’ll be using Vue CLI to scaffold our application. If you don’t know what Vue CLI is, you can watch this.

让我们创建一个新项目。 我将使用Vue CLI搭建我们的应用程序。 如果您不知道什么是Vue CLI,则可以观看此内容

  • vue create indicator

    Vue创建指示器

The CLI will ask us what technologies we want to use in our application, for this demo, I chose Router and Vuex. Next, hit enter and wait while your application installs its dependencies.

CLI将询问我们要在应用程序中使用哪些技术,对于本演示,我选择了Router和Vuex。 接下来,按Enter键,然后在您的应用程序安装其依赖项时等待。

We’ll also install nprogress to use as our loading indicator. You can use any loading indicator of your choice.

我们还将安装nprogress用作加载指示器。 您可以使用任何选择的加载指示器。

nprogress is a progress bar that attaches itself to the top of the page

nprogress是一个进度条,它附加在页面顶部

We won’t be using npm or yarn for this, let’s pull it straight from the CDN.

我们不会为此使用npmyarn ,我们直接将其从CDN中拉出。

In the created Vue CLI project, navigate to public/index.html file and add the snippet below before the closing head tag.

在创建的Vue CLI项目中,导航到public/index.html文件,并将以下代码段添加到head标签之前。

<link href="https://unpkg.com/nprogress@0.2.0/nprogress.css" rel="stylesheet" />
<script src="https://unpkg.com/nprogress@0.2.0/nprogress.js"></script>

使用nprogress (To use nprogress)

nprogress exposes a few API methods, but for this article we are only interested in the start and done methods. These methods start and stop the progress bar.

nprogress公开了一些API方法 ,但是对于本文,我们仅对startdone方法感兴趣。 这些方法启动和停止进度栏。

nprogress will also figure how to progress the loader, although this can be manually decided, we’ll stick with the default behaviour for demonstration.

尽管可以手动确定加载程序,但nprogress还将计算出如何加载程序,我们将使用默认行为进行演示。

使用路由器 (Using the Router)

When we use the router to add a progress bar to our website, the functionality we often want is: When a user navigates to a new page, the loader starts ticking at the top of the page showing the user the download progress of the next page.

当我们使用路由器将进度条添加到我们的网站时,我们经常需要的功能是:当用户导航到新页面时,加载程序开始在页面顶部打勾,向用户显示下一页的下载进度。 。

This is what we want:

这就是我们想要的:

The good thing is Vue router comes with hooks we can hook into that lets us do this.

好消息是Vue路由器带有挂钩,我们可以将其插入其中,以便我们执行此操作。

Open the src/router.js file and replace the default export with the code below.

打开src/router.js文件,并将默认导出替换为以下代码。

const router = new Router({
  routes: [
      { path: '/', name: 'home', component: Home },
      { path: '/about', name: 'about', component: About }
  ]
})

router.beforeResolve((to, from, next) => {
  // If this isn't an initial page load.
  if (to.name) {
      // Start the route progress bar.
      NProgress.start()
  }
  next()
})

router.afterEach((to, from) => {
  // Complete the animation of the route progress bar.
  NProgress.done()
})

export default router

When we hook to the beforeResolve route, we are telling the router to start nprogress once a page request happens. The afterEach hook tells the router that after a link has completely evaluated stop the progress bar, it shouldn’t care if the page request succeeds.

当我们挂接到beforeResolve路由时,我们告诉路由器一旦发生页面请求就启动nprogressafterEach挂钩告诉路由器,在完全评估了链接之后,停止进度条,它不会在乎页面请求是否成功。

使用您的HTTP库 (Using your HTTP library)

Another part of the application for which we like to add progress bars is when our user makes an AJAX request.

我们希望为其添加进度条的应用程序的另一部分是用户发出AJAX请求时。

Most HTTP libraries today have a sort of middleware or interceptor that fires before a request or response happens. Because of this, we can also hook into our library of choice.

如今,大多数HTTP库都有一种中间件或拦截器,可在请求或响应发生之前触发。 因此,我们也可以加入我们选择的库。

I prefer using axios. They call it interceptors. To install:

我更喜欢使用axios 。 他们称之为拦截器。 安装:

  • # for yarn

    #纱线
  • yarn add axios

    纱线添加轴
  • # for npm

    #for npm
  • npm install --save axios

    npm install-保存axios

Then we can configure axios to work like this.

然后,我们可以将axios配置为像这样工作。

// in HTTP.js
import axios from 'axios'

// create a new axios instance
const instance = axios.create({
  baseURL: '/api'
})

// before a request is made start the nprogress
instance.interceptors.request.use(config => {
  NProgress.start()
  return config
})

// before a response is returned stop nprogress
instance.interceptors.response.use(response => {
  NProgress.done()
  return response
})

export default instance

Then you can import and use the file above to handle your connections and get a progress bar every time a request is made.

然后,您可以导入并使用上面的文件来处理连接,并在每次发出请求时获得进度栏。

组件内的装载机 (Loaders within components)

There are times when we are not making a page request or an AJAX request. It may just be a browser dependent action that takes time.

有时我们不发出页面请求或AJAX请求。 这可能只是取决于浏览器的操作,需要花费时间。

Let’s create a custom DownloadButton component that can change its state to a loading state due to some external action.

让我们创建一个自定义的DownloadButton组件,由于某些外部动作,该组件可以将其状态更改为加载状态。

The component will take only one prop loading.

该组件将仅承受一次道具loading

<template>
  <DownloadButton :loading="loading">Download</DownloadButton>
</template>

Defining the component might look like this.

定义组件可能看起来像这样。

<template>
  <button class="Button" :disabled="loading">
      <svg v-if="loading" class="Button__Icon Button__Spinner" viewBox="...">
          <path d="..."/>
      </svg>
      <svg v-else class="Button__Icon" viewBox="0 0 20 20">
          <path d="..."/>
      </svg>
      <span v-if="!loading" class="Button__Content">
          <slot></slot>
      </span>
  </button>
</template>

<script>
export default {
  props: {
      loading: { type: Boolean }
  }
}
</script>

<style>
/* styles go here... duh! ;) */
</style>

Here’s a quick example.

这是一个简单的例子。

可重复使用的装载机的HOC (HOCs for Reusable Loaders)

We can create loaders as wrappers (HOCs) for our components that we can then modify its state via props.

我们可以为组件创建包装程序(HOC),然后可以通过props修改其状态。

These type of loaders are good for components that don’t affect the global state of your application, but you still want the user to feel connected to the action in place.

这些类型的加载程序非常适合那些不会影响应用程序全局状态的组件,但是您仍然希望用户感觉与已执行的操作相关联。

A quick example:

一个简单的例子:

// This loader will add an overlay with the text of 'Loading...'
const Loader = {
  template: `
      <div class="{'is-loading': loading}">
          <slot/>
      </div>
  `,
  props: ['loading']
}

const Stats = {
  template: `
      <Loader :loading="updating">
      ...
      </Loader>
  `,
  props: ['updating']
}

const app = new Vue({
  template: `
  <div class="widget">
      <Stats :updating="fetchingStats"/>
      <Button @click="fetchingStats = true">
          Latest stats
      </Button>
  </div>
  `,
})

Here’s an example of what it might look like:

这是一个可能看起来像的例子:

异步Vue组件 (Async Vue components)

Vue’s asynchronous components let you fetch components from the server only when you need them. Instead of serving end users components they might never use — they’re only given them what they need. You can read more about them in the official documentation.

Vue的异步组件使您仅在需要时才从服务器获取组件。 他们没有为最终用户提供可能永远不会使用的组件,而是仅向他们提供了所需的东西。 您可以在官方文档中阅读有关它们的更多信息。

Async components also come with native support for loading and error states, so no need for any special configuration here.

异步组件还提供了对加载和错误状态的本地支持,因此此处无需任何特殊配置。

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

To use async components with the method here, you need to use Vue router lazy loading.

要在此方法中使用异步组件,您需要使用Vue路由器延迟加载

结论 (Conclusion)

In this article we explored some of the ways to add a loading indicator to your Vue.js app.

在本文中,我们探讨了一些将加载指示器添加到Vue.js应用程序的方法。

翻译自: https://www.digitalocean.com/community/tutorials/add-loading-indicators-to-your-vuejs-application

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值