Load server-side data in your Vue 3 components

ยท 1 mins read ยท ย Vue

It is pretty common to load server-side data in our UI components in order to present dynamic content. In Vue 2 we have been using mostly created lifecycle hook to accomplish this but in Vue 3 there is no need to do so since we can simplify things a bit due to setup method.

Let's see a typical example with Vue 2:

import axios from 'axios';

export default {
  data: () => ({
    isLoading: true,
    posts: [],
  }),

  async created() {
    try {
      this.isLoading = true;

      const { data } = await axios.get('https://api.com/posts');

      this.posts = data;
    } catch (err) {
      // handle error here
    } finally {
      this.isLoading = false;
    }
  },
};

In Vue 3 there is not need to use created lifecycle hook anymore since we can use setup function directly. Actually, setup is called before the beforeCreate lifecycle hook. This is why we are super-safe to move such logic in setup method:

import { ref } from 'vue';
import axios from 'axios';

export default {
  setup() {
    const isLoading = ref(false);
    const posts = ref([]);

    const getPosts = async () => {
      try {
        isLoading.value = true;

        const { data } = await axios.get('https://api.com/posts');

        posts.value = data;
      } catch (err) {
        // handle error here
      } finally {
        isLoading.value = false;
     }
    };

    getPosts();

    return {
      posts,
      isLoading,
    };
  },
};

Notice that we need to use posts.value to apply a change to a reactive variable declared with ref. Don't worry though. We can still call them by using just their name in the template content:

<template>
  <div>
    <template v-if="posts.length > 0">
      <article v-for="post in posts" :key="post.id">
        <h1>{{post.title}}</h1>
      </article>
    </template>

    <h1 v-else>No posts found</h1>
  </div>
</template>

Newsletter

Get notified about latest posts and updates once a week!!