How to add async computed properties in Vue.js components?

Sometimes, we want to add async computed properties in Vue.js components.

In this article, we’ll look at how to add async computed properties in Vue.js components.

How to add async computed properties in Vue.js components?

To add async computed properties in Vue.js components, we should move out async code into methods and then put the synchronous code in the computed property method.

For instance, we write


<script>
//...
export default {
  //...
  computed: {
    sortedMessages() {
      return this.messages.sort((a, b) => {
        //...
      });
    },
  },
  data() {
    return {
      //...
      messages: [],
    };
  },
  async mounted() {
    const response = await api.get(`/users/${this.value.username}/message/`, {
      headers: {
        Authorization: "...",
      },
    });
    this.messages = response.data;
  },
  //...
};
</script>

to call the api.get method in the mounted hook.

Then we set the response.data returned by the returned promise to the this.messages reactive property.

And then we use the this.messages reactive property to create the sortedMessages computed property.

Conclusion

To add async computed properties in Vue.js components, we should move out async code into methods and then put the synchronous code in the computed property method.