Skip to content

Commit 0c5a6c4

Browse files
authored
Merge pull request #94 from Alanscut/usage-vue3
docs: update usage of axios in Vue 3
2 parents 6c03e50 + 7f52855 commit 0c5a6c4

File tree

1 file changed

+68
-5
lines changed

1 file changed

+68
-5
lines changed

README.md

Lines changed: 68 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ It only has a small benefit that it binds axios to the `vue` instance so you don
99

1010
## Support matrix
1111

12-
|VueJS \ VueAxios|1.x|2.x|3.x|
13-
|-|-|-|-|
14-
|1.x|✔|✔|✔|
15-
|2.x|✔|✔|✔|
16-
|3.x|❌|❌|✔|
12+
| VueJS \ VueAxios | 1.x | 2.x | 3.x |
13+
| ---------------- | -------- | -------- | -------- |
14+
| 1.x | ✔ | ✔ | ✔ |
15+
| 2.x | ✔ | ✔ | ✔ |
16+
| 3.x | ❌ | ❌ | ✔ |
1717

1818
## How to install:
1919
### ES6 Module:
@@ -43,6 +43,9 @@ app.use(VueAxios, axios)
4343
Just add 3 scripts in order: `vue`, `axios` and `vue-axios` to your `document`.
4444

4545
## Usage:
46+
47+
### in Vue 2
48+
4649
This wrapper bind `axios` to `Vue` or `this` if you're using single file component.
4750

4851
You can use `axios` like this:
@@ -60,4 +63,64 @@ this.$http.get(api).then((response) => {
6063
})
6164
```
6265

66+
### in Vue 3
67+
68+
This wrapper bind `axios` to `app` instance or `this` if you're using single file component.
69+
70+
in option API, you can use `axios` like this:
71+
72+
```js
73+
// App.vue
74+
export default {
75+
name: 'App',
76+
methods: {
77+
getList() {
78+
this.axios.get(api).then((response) => {
79+
console.log(response.data)
80+
})
81+
// or
82+
this.$http.get(api).then((response) => {
83+
console.log(response.data)
84+
})
85+
}
86+
}
87+
}
88+
```
89+
90+
however, in composition API `setup` we can't use `this`, you should use `provide` API to share the globally instance properties first, then use `inject` API to inject `axios` to `setup`:
91+
92+
```js
93+
// main.ts
94+
import { createApp } from 'vue'
95+
import App from './App.vue'
96+
import store from './store'
97+
import axios from 'axios'
98+
import VueAxios from 'vue-axios'
99+
100+
const app = createApp(App).use(store)
101+
app.use(VueAxios, axios)
102+
app.provide('axios', app.config.globalProperties.axios) // provide 'axios'
103+
app.mount('#app')
104+
105+
// App.vue
106+
import { inject } from 'vue'
107+
108+
export default {
109+
name: 'Comp',
110+
setup() {
111+
const axios: any = inject('axios') // inject axios
112+
113+
const getList = (): void => {
114+
axios
115+
.get(api)
116+
.then((response: { data: any }) => {
117+
console.log(response.data)
118+
});
119+
};
120+
121+
return { getList }
122+
}
123+
}
124+
```
125+
63126
Please kindly check full documention of [axios](https://github.com/axios/axios) too

0 commit comments

Comments
 (0)