vue 加载vuex \_适用于Vue / Vuex和Nuxt应用程序的复杂加载程序和进度管理

vue 加载vuex \

等待等待 (vue-wait)

Multiple Process Loader Management for Vue and (optionally) Vuex.

Vue和(可选)Vuex的多进程加载程序管理。

This project formerly known as vuex-loading.

该项目以前称为vuex-loading。

vue-waitv

vue-wait helps to manage multiple loading states on the page without any conflict. It's based on a very simple idea that manages an array (or Vuex store optionally) with multiple loading states. The built-in loader component listens its registered loader and immediately become loading state.

vue-wait帮助您管理页面上的多个加载状态,而不会发生任何冲突。 它基于一个非常简单的想法 ,该想法管理具有多个加载状态的阵列(或可选的Vuex存储)。 内置加载程序组件会侦听其注册的加载程序,并立即变为加载状态。

📦要求 (📦 Requirements)

🚀电源 (🚀 Power Supplies)

🔧安装 (🔧 Installation)

$ yarn add vue-wait
# or if you using npm
$ npm install vue-wait

📖用法 (📖 Usage)

import VueWait from 'vue-wait'

Vue.use(VueWait) // add VueWait as Vue plugin

Then you should register wait property (VueWait instance) to the Vue instance:

然后,您应该将wait属性( VueWait实例)注册到Vue实例:

new Vue({
  el: '#app',
  store,
  wait: new VueWait({
    // Defaults values are following:
    useVuex: false,              // Uses Vuex to manage wait state
    vuexModuleName: 'wait',      // Vuex module name

    registerComponent: true,     // Registers `v-wait` component
    componentName: 'v-wait',     // <v-wait> component name, you can set `my-loader` etc.

    registerDirective: true,     // Registers `v-wait` directive
    directiveName: 'wait',       // <span v-wait /> directive name, you can set `my-loader` etc.

  }),
});

♻️Vuex的用法 (♻️ Usage with Vuex)

Simply set useVuex parameter to true and optionally override vuexModuleName

只需将useVuex参数设置为true (可选)覆盖vuexModuleName

import VueWait from 'vue-wait'

Vue.use(Vuex)
Vue.use(VueWait) // add VueWait as Vue plugin

Then you should register VueWait module:

然后,您应该注册VueWait模块:

new Vue({
  el: '#app',
  store,
  wait: new VueWait({
    useVuex: true, // You must pass this option `true` to use Vuex
    vuexModuleName: 'vuex-example-module' // It's optional, `wait` by default.
  }),
});

Now VueWait will use Vuex store for data management which can be traced in Vue DevTools > Vuex

现在, VueWait将使用Vuex存储进行数据管理,可以在Vue DevTools > Vuex进行跟踪

♻️Nuxt.js的用法 (♻️ Usage with Nuxt.js)

Add vue-wait/nuxt to modules section of nuxt.config.js

添加vue-wait/nuxt到的模块部分nuxt.config.js

{
  modules: [
    // Simple usage
    'vue-wait/nuxt'

    // Optionally passing options in module configuration
    ['vue-wait/nuxt', { useVuex: true }]
  ],

  // Optionally passing options in module top level configuration
  wait: { useVuex: true }
}

ue VueWait选项 (🔁 VueWait Options)

You can use this options for customize VueWait behavior.

您可以使用此选项来自定义VueWait行为。

Option NameTypeDefaultDescription
accessorNameString"$wait"You can change this value to rename the accessor. E.g. if you rename this to $w, your VueWait methods will be accessible by $w.waits(..) etc.
useVuexBooleanfalseUse this value for enabling integration with Vuex store. When this value is true VueWait will store data in Vuex store and all changes to this data will be made by dispatching actions to store
vuexModuleNameString"wait"Name for Vuex store if useVuex set to true, otherwise not used.
registerComponentBooleantrueRegisters v-wait component.
componentNameString"v-wait"Changes v-wait component name.
registerDirectiveBooleantrueRegisters v-wait directive.
directiveNameString"v-wait"Changes v-wait directive name.
选项名称 类型 默认 描述
accessorName String "$wait" 您可以更改此值以重命名访问器。 例如,如果将其重命名为$w ,则$w.waits(..)等将可以访问您的VueWait方法。
useVuex Boolean false 使用此值可启用与Vuex存储的集成。 如果该值为true,则VueWait将在Vuex存储中存储数据,并且将通过调度存储操作来对此数据进行所有更改
vuexModuleName String "wait" 如果useVuex设置为true,则为Vuex存储的名称,否则不使用。
registerComponent Boolean true 注册v-wait组件。
componentName String "v-wait" 更改v-wait组件名称。
registerDirective Boolean true 注册v-wait指令。
directiveName String "v-wait" 更改v-wait指令名称。

🌈全局模板助手 (🌈 Global Template Helpers)

vue-wait provides some helpers to you to use in your templates. All features can be obtained from $wait property in Vue components.

vue-wait提供了一些帮助您在模板中使用。 可以从Vue组件的$ wait属性获得所有功能。

.any (.any)

Returns boolean value if any loader exists in page.

如果页面中存在任何加载器,则返回布尔值。

<template>
  <progress-bar v-if="$wait.any">Please wait...</progress-bar>
</template>
.waiting(loader String | Matcher) .is(loader String | Matcher).waiting(loader String | Matcher) (.is(loader String | Matcher) or .waiting(loader String | Matcher))

Returns boolean value if given loader exists in page.

如果页面中存在给定的加载器,则返回布尔值。

<template>
  <progress-bar v-if="$wait.is('creating user')">Creating User...</progress-bar>
</template>

You can use waiting alias instead of is.

您可以使用waiting别名代替is

<template>
  <div v-if="$wait.waiting('fetching users')">
    Fetching users...
  </div>
</template>

Also you can use matcher to make it more flexible:

您也可以使用匹配器使其更加灵活:

Please see matcher library to see how to use matchers.

请查看匹配器库以了解如何使用匹配器。

<template>
  <progress-bar v-if="$wait.is('creating.*')">Creating something...</progress-bar>
</template>
.is(loaders Array<String | Matcher>).waiting(loaders Array<String | Matcher>) (.is(loaders Array<String | Matcher>) or .waiting(loaders Array<String | Matcher>))

Returns boolean value if some of given loaders exists in page.

如果页面中存在某些给定的加载器,则返回布尔值。

<template>
  <progress-bar v-if="$wait.is(['creating user', 'page loading'])">Creating User...</progress-bar>
</template>
.start(loader String) (.start(loader String))

Starts the given loader.

启动给定的加载器。

<template>
  <button @click="$wait.start('creating user')">Create User</button>
</template>
.end(loader String) (.end(loader String))

Stops the given loader.

停止给定的加载器。

<template>
  <button @click="$wait.end('creating user')">Cancel</button>
</template>
.progress(loader String, current [, total = 100]) (.progress(loader String, current [, total = 100]))

Sets the progress of the given loader.

设置给定加载器的进度。

<template>
  <progress min="0" max="100" :value="$wait.percent('downloading')" />
  <button @click="$wait.progress('downloading', 10)">Set progress to 10</button>
  <button @click="$wait.progress('downloading', 50)">Set progress to 50</button>
  <button @click="$wait.progress('downloading', 50, 200)">Set progress to 50 of 200 (25%)</button>
</template>
完成进度 (Completing the Progress)

To complete the progress, current value should be set bigger than 100. If you total is given, current must be bigger than total.

要完成进度, current值应设置为大于100 。 如果给出total ,则current必须大于total

<button @click="$wait.progress('downloading', 101)">Set as downloaded (101 of 100)</button>

or

要么

<button @click="$wait.progress('downloading', 5, 6)">Set as downloaded (6 of 5)</button>
.percent(loader String) (.percent(loader String))

Returns the percentage of the given loader.

返回给定加载器的百分比。

<template>
  <progress min="0" max="100" :value="$wait.percent('downloading')" />
</template>

🏹指令 (🏹 Directives)

You can use directives to make your template cleaner.

您可以使用指令使模板更整洁。

v-wait:visible='"loader name"' (v-wait:visible='"loader name"')

Shows if the given loader is loading.

显示给定的加载程序是否正在加载。

<template>
  <progress-bar v-wait:visible='"creating user"'>Creating User...</progress-bar>
</template>
v-wait:hidden='"loader name"'v-wait:visible.not='"loader name"' (v-wait:hidden='"loader name"' or v-wait:visible.not='"loader name"')

Hides if the given loader is loading.

如果给定的加载器正在加载,则隐藏。

<template>
  <main v-wait:hidden='"creating *"'>Some Content</main>
</template>
v-wait:disabled='"loader name"' (v-wait:disabled='"loader name"')

Sets disabled="disabled" attribute to element if the given loader is loading.

如果给定的加载器正在加载,则将disabled="disabled"属性设置为element。

<template>
  <input v-wait:disabled="'*'" placeholder="Username" />
  <input v-wait:disabled="'*'" placeholder="Password" />
</template>
v-wait:enabled='"loader name"'v-wait:disabled.not='"loader name"' (v-wait:enabled='"loader name"' or v-wait:disabled.not='"loader name"')

Removes disabled="disabled" attribute to element if the given loader is loading.

如果给定的加载程序正在加载,则将元素的disabled="disabled"属性移除。

<template>
  <button v-wait:enabled='"creating user"'>Abort Request</button>
</template>
v-wait:click.start='"loader name"' (v-wait:click.start='"loader name"')

Starts given loader on click.

单击启动给定的加载器。

<template>
  <button v-wait:click.start='"create user"'>Start loader</button>
</template>
v-wait:click.end='"loader name"' (v-wait:click.end='"loader name"')

Ends given loader on click.

单击结束给定的加载程序。

<template>
  <button v-wait:click.end='"create user"'>End loader</button>
</template>
v-wait:toggle='"loader name"' (v-wait:toggle='"loader name"')

Toggles given loader on click.

在点击时切换给定的加载器。

<template>
  <button v-wait:toggle='"flip flop"'>Toggles the loader</button>
</template>
v-wait:click.progress='["loader name", 80]' (v-wait:click.progress='["loader name", 80]')

Sets the progress of given loader on click.

单击时设置给定加载器的进度。

<template>
  <button v-wait:click.progress='["downloading", 80]'>Set the "downloading" loader to 80</button>
</template>

🔌加载动作和Getter映射器 (🔌 Loading Action and Getter Mappers)

vue-wait provides mapWaitingActions and mapWaitingGetters mapper to be used with your Vuex stores.

vue-wait提供了与您的Vuex商店一起使用的mapWaitingActionsmapWaitingGetters映射器。

Let's assume you have a store and async actions called createUser and updateUser. It will call the methods you map and will start loaders while action is resolved.

假设您有一个名为createUserupdateUser的存储和异步操作 。 它将调用您映射的方法,并在解决操作后启动加载程序。

import { mapWaitingActions, mapWaitingGetters } from 'vue-wait'

// ...
  methods: {
    ...mapWaitingActions('users', {
      getUsers: 'loading users',
      createUser: 'creating user',
      updateUser: 'updating user',
    }),
  },
  computed: {
    ...mapWaitingGetters({
      somethingWithUsers: [
        'loading users',
        'creating user',
        'updating user',
      ],
      deletingUser: 'deleting user',
    }),
  }
// ...

☢️高级吸气剂和动作用法 (☢️Advanced Getters and Actions Usage)

The Vuex module name is wait by default. If you've changed on config, you should get it by rootGetters['<vuex module name>/is'] or rootGetters['<vuex module name>/any'].

Vuex模块名称默认为wait 。 如果更改了配置,则应通过rootGetters['<vuex module name>/is']rootGetters['<vuex module name>/any']

You can access vue-wait's Vuex getters using rootGetters in Vuex.

您可以使用rootGetters中的rootGetters访问vue-wait的Vuex getter。

getters: {
  cartOperationInProgress(state, getters, rootState, rootGetters) {
    return rootGetters['wait/is']('cart.*');
  }
},

And you can start and end loaders using wait actions. You must pass root: true option to the dispatch method.

您可以使用wait操作来启动和结束加载程序。 您必须将root: true选项传递给dispatch方法。

actions: {
  async addItemToCart({ dispatch }, item) {
    dispatch('wait/start', 'cart.addItem', { root: true });
    await CartService.addItem(item);
    dispatch('wait/end', 'cart.addItem', { root: true });
  }
},
waitFor(loader String, func Function [,forceSync = false]) (waitFor(loader String, func Function [,forceSync = false]))

Decorator that wraps function, will trigger a loading and will end loader after the original function (func argument) is finished.

包装函数的装饰器将触发加载,并在原始函数( func参数)完成后结束加载器。

By default waitFor return async function, if you want to wrap default sync function pass true in last argument

默认情况下, waitFor返回异步函数,如果要包装默认同步函数,则在最后一个参数中传递true

Example using with async function

与异步功能一起使用的示例

...
methods: {
  fetchDataFromApi: waitFor('fetch data', async function () {
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    // do work here
    await sleep(3000);
    // simulate some api call
    this.fetchResponse = Math.random()
  })
}
...

See also examples/wrap-example

另请参阅examples/wrap-example

💧使用v-wait组件 (💧 Using v-wait Component)

If you disable registerComponent option then import and add v-wait into components

如果禁用registerComponent选项,则导入v-wait并将其添加到组件中

import vLoading from 'vue-wait/src/components/v-wait.vue'
components: {
  'v-wait': vLoading
}

In template, you should wrap your content with v-wait component to show loading on it.

在模板中,应使用v-wait组件包装内容以显示其上的负载。

<v-wait for='fetching data'>
  <template slot='waiting'>
    This will be shown when "fetching data" loader starts.
  </template>

  This will be shown when "fetching data" loader ends.
</v-wait>

Better example for a button with loading state:

具有加载状态的button更好示例:

<button :disabled='$wait.is("creating user")'>
  <v-wait for='creating user'>
    <template slot='waiting'>Creating User...</template>
    Create User
  </v-wait>
</button>

⚡️制作可重复使用的加载器组件 (⚡️ Making Reusable Loader Components)

With reusable loader components, you will be able to use custom loader components as example below. This will allow you to create better user loading experience.

使用可重用的加载器组件,您将能够使用自定义加载器组件,如下例所示。 这将使您创建更好的用户加载体验

In this example above, the tab gets data from back-end, and the table loads data from back-end at the same time. With vue-wait, you will be able to manage these two seperated loading processes easily:

在上面的示例中, 选项卡从后端获取数据 ,而表同时从后端加载数据 。 使用vue-wait ,您将能够轻松管理以下两个独立的加载过程:

<template lang='pug'>
  <div>
    <v-wait for="fetching tabs">
      <template slot="waiting">
        <b-tabs>
          <template slot="tabs">
            <b-nav-item active="active" disabled>
              <v-icon name="circle-o-notch" spin="spin" />
            </b-nav-item>
          </template>
        </b-tabs>
      </template>
      <b-tabs>
        <template slot="tabs">
          <b-nav-item v-for="tab in tabs">{{ tab.name }}</b-nav-item>
        </template>
      </b-tabs>
    </v-wait>
    <v-wait for="fetching data">
      <table-gradient-spinner slot="waiting" />
      <table>
        <tr v-for="row in data">
          <!-- ...-->
        </tr>
      </table>
    </v-wait>
  </div>
</template>

You may want to design your own reusable loader for your project. You better create a wrapper component called my-waiter:

您可能要为您的项目设计自己的可重用加载器。 您最好创建一个名为my-waiter的包装器组件:

<!-- MySpinner.vue -->
<i18n>
  tr:
    loading: Yükleniyor...
  en:
    loading: Loading...
</i18n>

<template>
  <div class="loading-spinner">
    <v-icon name="refresh" spin="spin" />
    <span>{{ $t('loading') }}</span>
  </div>
</template>

<style scoped lang="scss">
  .loading-spinner {
    opacity: 0.5;
    margin: 50px auto;
    text-align: center;
    .fa-icon {
      vertical-align: middle;
      margin-right: 10px;
    }
  }
</style>

Now you can use your spinner everywhere using slot='waiting' attribute:

现在,您可以使用slot='waiting'属性在所有地方使用微调器:

<template lang="pug">
  <v-wait for="fetching data">
    <my-waiter slot="waiting" />
    <div>
      <p>My main content after fetching data...</p>
    </div>
  </v-wait>
</template>

with与外部微调器库一起使用 (📦 Using with external spinner libraries)

You can use vue-wait with another spinner libraries like epic-spinners or other libraries. You just need to add slot="waiting" to the component and Vue handles rest of the work.

您可以将vue-wait与其他旋转器库(如史诗般的旋转器)或其他库一起使用。 您只需要向组件添加slot="waiting" ,Vue即可处理其余工作。

First register the component,

首先注册组件,

import { OrbitSpinner } from 'epic-spinners';
Vue.component('orbit-spinner', OrbitSpinner);

Then use it in your as a v-wait's waiting slot.

然后将其用作v-waitwaiting槽。

<v-wait for='something to load'>
  <orbit-spinner
    slot='waiting'
    :animation-duration="1500"
    :size="64"
    :color="'#ff1d5e'"
  />
</v-wait>

... and done!

... 并做了!

For other libraries you can use, please see Loaders section of vuejs/awesome-vue.

对于您可以使用的其他库,请参见vuejs / awesome-vue的 Loaders部分

🚌运行示例 (🚌 Run example)

Use npm run dev-vuex, npm run dev-vue or npm run dev-wrap commands. for running examples locally.

使用npm run dev-vuexnpm run dev-vuenpm run dev-wrap命令。 用于在本地运行示例。

翻译自: https://vuejsexamples.com/complex-loader-and-progress-management-for-vue-vuex-and-nuxt-applications/

vue 加载vuex \

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值