4

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

0

2 Answers 2

5

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)
   });
  }
};
Sign up to request clarification or add additional context in comments.

Comments

2

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.

4 Comments

thx, but I use the composition API, it seems that import must be used on that page.
Yes, that was the point of my explanation. It doesn't work without an import
But there are other ways to give access through the root component in Vue 3: stackoverflow.com/questions/60202724/…
oh! maybe use provide/inject is goods idea! very thx!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.