npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vue-loadable

v0.2.0

Published

Improves your loading state flow by providing methods and helpers to manage it.

Downloads

78

Readme

vue-loadable

Build Status License Library minified size Library minified + gzipped size FOSSA Status

vue-loadable improves your loading state flow by providing methods and helpers to manage it.

<template>
  <p v-if="$isLoading('initialize')">Initializing...</p>
  <div v-else>
    <!-- Loaded content... -->
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import { loadable, mapLoadableMethods } from 'vue-loadable';

export default {
  ...,

  methods: {
    async initialize () {
      // Set initialize state as loading on async function start.
      this.$setLoading('initialize');

      try {
        await this.$store.dispatch('users/fetchUsers');
      } catch (_) {}

      // Unset initialize state as loading on async function end.
      this.$unsetLoading('initialize');
    },

    // `loadable` decorator can automate this process.
    initialize: loadable(async function () {
      await this.$store.dispatch('users/fetchUsers');
    }, 'initialize'),

    // An there's `mapLoadableMethods` to map methods into loadable methods (works with Vuex too).
    ...mapLoadableMethods(
      mapActions('users', {
        initialize: 'fetchUsers'
      })
    )
  },
  mounted () {
    this.initialize();
  }
};

Installation

This library is published in the NPM registry and can be installed using any compatible package manager.

npm install --save vue-loadable

# Use the command below if you're using Yarn.
yarn add vue-loadable

Installation from CDN

This module has an UMD bundle available through JSDelivr and Unpkg CDNs.

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-loadable"></script>

<script>
  // module will be available through `VueLoadable` object.
  console.log(VueLoadable);

  Vue.use(VueLoadable);
</script>

Installation on Vue

vue-loadable need to be installed to enable loadable methods, loadable decorator and mapLoadableMethods helper.

To install globally, just pass default exported object as argment to Vue.use.

import Vue from 'vue';
import Loadable from 'vue-loadable';

Vue.use(Loadable);

You can install it locally instead with LoadableMixin mixin.

<script>
import { LoadableMixin } from 'vue-loadable';

export default {
  mixins: [LoadableMixin],
};
</script>

API

  • loadable decorates a function to change loading state during its execution. It sets the state as loading when function inits and unsets when it throws an error, when it resolves or when it returns a value.

    Second argument is the loading state name, is "unknown" when it's not defined.

    Vue.component('SignInForm', {
      methods: {
        signIn: loadable(async function(name) {
          // ...
        }, 'signIn'),
      },
    
      async mounted() {
        this.$isLoading('signIn');
        //=> false
    
        const promise = this.signIn('Vitor');
    
        this.$isLoading('signIn');
        //=> true
    
        await promise;
    
        this.$isLoading('signIn');
        //=> false
      },
    });

    It passes down the function arguments, rejects the errors and resolves the returned value.

    async function confirmUsername(username: string): Promise<boolean> {
      // ...
    }
    
    export default {
      methods: {
        // Returns a function with same signature, but handling loading states.
        confirm: loadable(confirmUsername, 'confirmation'),
      },
      async mounted(): Promise<void> {
        try {
          const isConfirmed = await this.confirm('VitorLuizC');
          this.$router.push(isConfirmed ? '/checkout' : '/confirmation');
        } catch (error) {
          new Rollbar.Error(error).send();
        }
      },
    };
    type Method =
      | ((...args: any[]) => any)
      | ((this: Vue, ...args: any[]) => any);
    
    type LoadableMethod<T extends Method> = (
      this: Vue,
      ...args: Parameters<T>
    ) => ReturnType<T> extends Promise<any>
      ? ReturnType<T>
      : Promise<ReturnType<T>>;
    
    const loadable: <T extends Method>(
      method: T,
      state?: string,
    ) => LoadableMethod<T>;
  • mapLoadableMethods maps methods into loadable ones that triggers loading states, it works pretty well with Vuex.

    It uses method's names as loading state name.

    <template>
      <div v-if="$isLoading('signInUser')">
        Carregando...
      </div>
      <div v-else>
        <SignedUserArea />
      </div>
    </template>
    
    <script>
    import { mapActions } from 'vuex';
    import { mapLoadableMethods } from 'vue-loadable';
    
    export default {
      methods: mapLoadableMethods(
        mapActions([
          'signInUser',
          'signUpUser'
        ])
      )
    };
    // `Method` and `LoadableMethod` are defined at `loadable` type definitions.
    
    type Methods = Record<string, Method>;
    
    type LoadableMethods<T extends Methods> = {
      [K in keyof T]: LoadableMethod<T[K]>;
    };
    
    const mapLoadableMethods: <T extends Methods>>(
      methods: T,
    ) => LoadableMethods<T>;
  • $isLoading is a method to check if a state is loading.

    Argument is the loading state name, is "unknown" when it's not defined.

    <template>
      <v-spinner v-if="$isLoading('initialize')" />
      <sign-in-form v-else @click="onClickSignIn" ... />
    </template>
    
    <script>
    // ...
    
    export default {
      methods: {
        ...,
        onClickSignIn () {
          if (!this.$isLoading('signIn')) // Call `signIn` only if its not loading.
            return;
    
          this.signIn();
        }
      }
    };
    interface Vue {
      $isLoading(state?: string): boolean;
    }
  • $isLoadingAny is a method to check if any state is loading.

    <template>
      <v-spinner v-if="$isLoadingAny()" />
      <div>
        <sign-in-or-sign-up-form @signIn="onSignIn" @signUp="onSignUp" />
      </div>
    </template>
    
    <script>
    // ...
    
    export default {
      methods: {
        ...,
        onSignUp () {
          if (!this.$isLoadingAny())
            return;
    
          this.signUp();
        },
        onSignIn () {
          if (!this.$isLoadingAny())
            return;
    
          this.signIn();
        }
      }
    };
    interface Vue {
      $isLoadingAny(): boolean;
    }
  • $setLoading is a method to set state as loading.

    Argument is the loading state name, is "unknown" when it's not defined.

    export default {
      methods: {
        ...,
        async onSubmit () {
          this.$setLoading('submission'); // set submission state as loading.
    
          await services.submit(this.fields);
        }
      }
    };
    interface Vue {
      $setLoading(state?: string): void;
    }
  • $unsetLoading is a method to unset state as loading.

    Argument is the loading state name, is "unknown" when it's not defined.

    export default {
      methods: {
        ...,
        async onSubmit () {
          try {
            await services.submit(this.fields);
          } catch {}
    
          this.$unsetLoading('submission'); // unset submission state as loading.
        }
      }
    };
    interface Vue {
      $unsetLoading(state?: string): void;
    }

License

Released under MIT License.

FOSSA Status