vue-js-vue-axios-快速上手

上一级页面:vue-js-学习索引

本系列关注前端部分,根据学习路线图达到学习Vue.js的目的

developer路线图developer-roadmap/translations/chinese at master · kamranahmedse/developer-roadmap

前言

官方文档

官方的npm仓库:vue-axios - npm (npmjs.com)

快速上手

直接看视频吧,新手会用就行了,见视频p1的57分钟

安装

1
npm install --save axios vue-axios

使用示例

按照官方示例来,vue-axios - npm (npmjs.com)

首先导入到vue的全局/src/main.js

1
2
3
4
5
6
import axios from "axios";
import vueAxios from "vue-axios";

const app = createApp(App);
app.use(vueAxios, axios);

Pasted image 20230127181349.png

组合式api

如果你使用组合式api,那么需要这么写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App).use(store)
app.use(VueAxios, axios)
app.provide('axios', app.config.globalProperties.axios) // provide 'axios'
app.mount('#app')

// App.vue
import { inject } from 'vue'

export default {
name: 'Comp',
setup() {
const axios: any = inject('axios') // inject axios

const getList = (): void => {
axios
.get(api)
.then((response: { data: any }) => {
console.log(response.data)
});
};

return { getList }
}
}

参考、引用、致谢