Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue composition API use VueAxios?

I am in main.js importing vue-axios

main.js

import { createApp } from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import App from './App.vue';

const app = createApp(App);

app.use(VueAxios, axios);
app.mount('#app');

and App.vue

export default {
  name: 'App',
  setup() {
   axios.get('xxxx').then((res) => {console.log(res)}); // is not working
  }
};

but it seems Vue composition API setup can't get axios? So it must be used in App.vue import axios from 'axios'?

import axios from 'axios';
 
export default {
  name: 'App',
  setup() {
   axios.get('xxxx').then((res) => {console.log(res)});
  }
};

My environment is vite

like image 271
Ray Avatar asked Mar 01 '23 21:03

Ray


2 Answers

generally I'd do something like this ( except I modularize all the api calling into a "service" rather than inlining it into the view code.)

import axios from 'axios';
import {onMounted} from 'vue'
 
export default {
  name: 'App',
  setup() {

   onMounted(async () => {
     let res = await axios.get('xxxx')
     console.log(res)
   });
  }
};
like image 138
Keith Nicholas Avatar answered Mar 11 '23 10:03

Keith Nicholas


This wouldn't work in any version of Vue without an import:

axios.get(...)

Even in Vue 2, you have to use one of these if you use vue-axios:

this.axios.get(...)
this.$http.get(...)
Vue.axios.get(...)

The composition API has no this access in the component, so vue-axios doesn't help much.

like image 39
Dan Avatar answered Mar 11 '23 10:03

Dan