Axios in Vue3 setup

author

Devmnj • Wed Dec 15 2021

0 min read

Vue 3is a progressive framework for web development, this opensource project is a power tool in web developer kit. It’s fast, lightweight and easy to learn. Version 3 has many performance upgrade fromVue 2.

For consuming API in Vue I have two option go with Fetch or use axios. Usingaxiosin Vue3 script setup is similar to Vue2 , but you may mess up withthisandvalue.

How to use axios in Vue 3 setup

In the composition API setup , we can setup Axios on mounted life cycle hook as follows and use.valueto assign the value to reactive property.

Source code

const {  onMounted, ref} = require("vue");
 const axios = require("axios");
 export default {
 
   setup( ) {
    const info=ref([])
    onMounted(async () => {
      await axios
          .get('https://jsonplaceholder.typicode.com/posts')
          .then(response => {
            info.value = response.data
 
          })
      console.log(info)
    })
     return {
      info
     }
   }
 }