0.0.1 • Published 1 year ago

vue2-suspense v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Vue Suspense

A package to use with use with Vuejs 2 to load data while is showing a loading placeholder. Also offers an error fallback template.

Installation

Install vue2-suspense with NPM

  npm install vue2-suspense

And use it into your main file

import Vue from 'vue';

import VueSuspense from 'vue2-suspense';

Vue.use(VueSuspense);

API Reference

Props

NameTypeDescription
idstring, number, boolean, array, objectUsed as two way binding object (v-model).
promisePromiseRequired. A promise object or a function that returns a promise. Used to load the data into the component.
tagstringDefault: div. The name of the tag used as wrapper for the component.

Events

NameDescription
inputEmitted after load the data and passed as payload.
on-errorEmitted after an error was caught with the error as payload.

Slots

NameDescription
defaultUsed when data is loaded and there are not errors.
loadingUsed when data is being loading. By default, show an animated spinner icon.
errorUsed when an error happened.

Example

<template>
  <div id="app">
    <vue-suspense v-model="dataLoaded" :promise="loadData()" :key="key">
      <ul>
        <li v-for="number in dataLoaded" :key="number">{{ number }}</li>
      </ul>
      <template #error="{error}">
        {{ error }}
      </template>
      <!-- <template #loading>
        Loading numbers...
      </template> -->
    </vue-suspense>
    <button @click="keyFlag=!keyFlag">Reload</button>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  name: 'App',
  data: () => ({
    keyFlag: false,
    dataLoaded: [],
  }),
  computed: {
    key() {
      return this.keyFlag ? 1 : -1;
    }
  },
  methods: {
    async loadData() {
      const randomSeconds: number = Math.floor(Math.random() * 6) + 1;
      console.log(randomSeconds);
      await new Promise((resolve) => setTimeout(resolve, randomSeconds * 1000));
      if (randomSeconds >= 5) {
        return Promise.reject('Timeout error');
      }
      return Array.from(Array(10), (_, index) => index + 1);
    }
  }
});
</script>

See an example here.

Author

Feel free to open a PR or create an issue to contribute to this package.

License

MIT