question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Have you tried vue-async-computed ? It is incredibly awesome, because it allows asynchronous computed properties. Among other things, this makes it incredibly easy to source your Vue data from AJAX calls. I will try to convince you that this feature is SO good, that it is worthy of including in Vue’s core instead of being relegated to this lowly plugin.

Code sample

Here’s an example application that uses two properties to seamlessly interact with the server. Actions are “dispatched” by setting properties. (I clump mine in a object called “active”.) This flags them as dirty, causing Vue to automatically re-compute any async properties that depend on that property.

Here, $vm.active.lang is a read-write property containing the current language. The $vm.i18n property contains all the i18n strings. Changing $vm.active.lang causes Vue to pull the appropriate language file from the server and update the text on the page. Is that simple or what?

<template>
  <p>{{i18n.hello}}, {{CurrentUser.name}}!</p>
</template>

<script>
const Ajax = (url, opts) => window.fetch(url, opts).then((response) => response.json())

let App = new Vue({
  el: '#app',
  data () {
    return {
      active: {
        lang: 'en'
      }
    }
  },
  asyncComputed: {
    i18n () {
      return Ajax('/lang/' + this.active.lang)
    },
    CurrentUser () {
      return Ajax('/logged_in_user.json', {credentials: 'include'})
    }
  }
})
</script>

I also left in some code that fetches the current user from the server so we can greet the user by name.

How will it make current work-arounds straightforward?

Right now, it requires conceiving the idea of “async properties”, searching the web to see if someone has done it, and then using this plugin. But I really think it is extremely elegant and intuitive, and having it baked into Vue’s core and documented in the Vue guide would encourage more people to think, “Oh, this is a really great way to get data from my server into Vue” and would simplify a lot of people’s spaghetti code, which would make the world a better place.

What potential bugs and edge cases does it help to avoid?

Many beginners (and even experts) still have not fully committed to using a Flux-architecture framework, or are dealing with horrendous legacy applications and “vueifying” pieces of it as we go. But it is well established that this unidirectional data flow from server to client is a great idea and simplifies state management and reduces spaghetti code. Adding native support for asynchronous properties would enable and promotes a very simple, declarative unidirectional server-to-client data flow that has the advantage of being easily injected into existing legacy code without having to learn a new framework.

I’m sure there are other uses for asynchronous computed properties too (dispatching a long-running task to a WebWorker comes to mind) but I’ve only used it for AJAX so that’s the example I’ve used.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:15
  • Comments:18 (7 by maintainers)

github_iconTop GitHub Comments

83reactions
yyx990803commented, Nov 2, 2016

I like the idea… maybe we can simply make normal computed accept returning a Promise.

29reactions
egasimuscommented, May 3, 2018

+1 for a native solution

  1. how can user declare a default value when promise is not resolved?
computed: {
  syncProperty () { return 'foo' },
  promisedProperty () { return Promise.resolve('foo') }, // default is undefined
  promisedPropertyWithDefault: {
    value () { return Promise.resolve('foo') },
    default: 'bar'
  },
  async asyncProperty () { return await Promise.resolve('foo') },
  asyncPropertyWithDefault: {
    async value () { return await Promise.resolve('foo') },
    default: 'bar'
  }
}
  1. should vue support a builtin throttle promise to handle events like keychange, mousemove?

even if a promise-based implementation of throttled events makes sense in particular scenarios, imho it’s tangential to the main use case here. it would be sufficient to add a minimal core implementation that lets you asynchronously fetch data with the absolute minimum amount of boilerplate - then see what other clever and unexpected (but semantically correct) uses people put it to

  1. should vue support a builtin callback when certain promise is resolved?

can you provide a scenario where this is necessary - as opposed to normal vue-agnostic use of promises? watch seems a good way of doing this without expanding the api surface

  1. how to inspect whether the async property is resolving or resolved?

default value + callback on resolve is good enough for the core minimal use case

overall vue-async-computed is a step in the right direction, and core support for this would be a major step forward, seeing how promises and async/await are now a core part of our language workflow

Read more comments on GitHub >

github_iconTop Results From Across the Web

Async computed properties for Vue.js - GitHub
Just like normal computed properties, async computed properties keep track of their dependencies, and are only recalculated if those dependencies change. But ...
Read more >
Async Computed in Components - VueJS? - Stack Overflow
Computed properties are basically functions that cache their results so that they don't have to be calculated every time they are needed.
Read more >
vue-async-computed - npm
vue-async-computed. TypeScript icon, indicating that this package has built-in type declarations. 3.9.0 • Public • Published 2 years ago.
Read more >
How To Use Asynchronous Computed Properties in Vue.js ...
In this article, you applied vue-async-computed to a Vue project to utilize asyncComputed . Some of the advantages and disadvantages of this ...
Read more >
asyncComputed - VueUse
As opposed to Vue's built-in computed function, re-evaluation of the async computed value is triggered whenever dependencies are changing, regardless of whether ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found