Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Computed in Components - VueJS?

I'm finding a solution to async computed method in Components:

Currently, my component is:

<div class="msg_content">    {{messages}} </div>  <script> export default {   computed: {     messages: {       get () {         return api.get(`/users/${this.value.username}/message/`, {'headers': { 'Authorization': 'JWT ...' }})         .then(response => response.data)       }     }   }, } </script> 

Result: {}

How to rewrite it in Promise mode? Because I think we can async computed by writing into Promise mode.

like image 553
KitKit Avatar asked Feb 06 '18 10:02

KitKit


People also ask

Can computed property be async Vue?

This feature is synchronous. However, the vue-async-computed package allows you to create and consume asynchronous computed properties in your components by binding the resolved value of a Promise to a component property.

How do I use async await with Vue components?

To use async and await in Vue. js, we can add async and await in our component methods and hooks. to make the created hook an async method. We use await to wait for the getA method to finish before running the rest of the code.

What is async component in Vue?

The resulting AsyncComp is a wrapper component that only calls the loader function when it is actually rendered on the page. In addition, it will pass along any props and slots to the inner component, so you can use the async wrapper to seamlessly replace the original component while achieving lazy loading.

Is Vue synchronous or asynchronous?

You might know Vue updates reactively: when you change a value, the DOM is automatically updated to reflect the latest value. Vue does these updates asynchronously. In contrast, a test runner like Jest runs synchronously. This can cause some surprising results in tests.


1 Answers

Computed properties are basically functions that cache their results so that they don't have to be calculated every time they are needed. They updated automatically based on the reactive values they use.

Your computed does not use any reactive items, so there's no point in its being a computed. It returns a Promise now (assuming the usual behavior of then).

It's not entirely clear what you want to achieve, but my best guess is that you should create a data item to hold response.data, and make your api.get call in the created hook. Something like

export default {   data() {       return {         //...         messages: []       };   },   created() {     api.get(`/users/${this.value.username}/message/`, {         'headers': {           'Authorization': 'JWT ...'         }       })       .then(response => this.messages = response.data);   } } 
like image 69
Roy J Avatar answered Oct 06 '22 16:10

Roy J