Render Blocks Based On The Status Of A Promise – vue-await

Render Blocks Based On The Status Of A Promise – vue-await

The vue-await allows you to render blocks based on the status of a Promise.

vue-await

Render blocks based on the status of a Promise. See a demo.

<template>
  <Await :p="prom">
    <p>Waiting...</p>
    <p slot="then" slot-scope="[result]">Success: {{result}}</p>
    <p slot="catch" slot-scope="[error]">Error: {{error}}</p>
    <p slot="none">(promise is null)</p>
  </Await>
</template>

<script>
export default {
  data() {
    return {
      prom: fetch('http://thecatapi.com/api/images/get'),
    };
  },
}
</script>

Installation

npm install --save vue-await

Prior Art

Caveats

  • Because slots cannot live at the root of a template, this component introduces one extra div of nesting. This has the potential to break some css rules using the > immediate child selector.
  • Promises can resolve and reject with multiple arguments, so the slot-scope value for slot="then" and slot="catch" will always be an array. You can destructure it with slot-scope="[result]" if you like.

Future Work

This would likely be better as a directive along the lines of v-if:

<div v-await="todosPromise">
    <p>loading...</p>
</div>
<div v-then="todos">
    <TodoList :data="todos" />
</div>
<div v-catch="error">
    <p>Uh oh, something went wrong: {{ error }}</p>
</div>

This would require a patch to the Vue core library. I intend to look into this, but don't have time just now. Note to self: check out here

Project setup

npm install

Compiles and hot-reloads for development

npm run serve

Compiles and minifies for production

npm run build

Lints and fixes files

npm run lint

Run your unit tests

npm run test:unit

Github Repository

Tags: #Vue.js