最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue composition API use VueAxios? - Stack Overflow

programmeradmin1浏览0评论

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 position 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

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 position 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

Share Improve this question edited Nov 28, 2020 at 7:36 Dan 63.1k18 gold badges110 silver badges119 bronze badges asked Nov 26, 2020 at 1:50 RayRay 992 silver badges13 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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)
   });
  }
};

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 position API has no this access in the ponent, so vue-axios doesn't help much.

发布评论

评论列表(0)

  1. 暂无评论