|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | + <head> |
| 4 | + <meta charset="UTF-8" /> |
| 5 | + <meta http-equiv="X-UA-Compatible" content="IE=edge" /> |
| 6 | + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
| 7 | + <title>Vue-Axios in Vue 3 with Composition API</title> |
| 8 | + </head> |
| 9 | + |
| 10 | + <body> |
| 11 | + <div id="app"></div> |
| 12 | + |
| 13 | + <script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.min.js" ></script> |
| 14 | + <script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js" ></script> |
| 15 | + <script src="../../../dist/vue-axios.min.js"></script> |
| 16 | + |
| 17 | + <script type="text/javascript"> |
| 18 | + const { ref, inject, provide } = Vue |
| 19 | + const app = Vue.createApp({ |
| 20 | + template: ` |
| 21 | + <button @click="reset">reset msg</button> |
| 22 | + <button @click="getMsg1">get msg by injectAxios</button> |
| 23 | + <button @click="getMsg2">get msg by inject$http</button> |
| 24 | + <div v-html="msg"></div> |
| 25 | + `, |
| 26 | + setup() { |
| 27 | + let msg = ref('Hello, Composition API!') |
| 28 | + const injectAxios = inject('axios') |
| 29 | + const inject$http = inject('$http') |
| 30 | + |
| 31 | + const getMsg1 = () => { |
| 32 | + injectAxios |
| 33 | + .get('http://localhost:3000/greet') |
| 34 | + .then((res) => (msg.value = res.data)) |
| 35 | + } |
| 36 | + const getMsg2 = () => { |
| 37 | + inject$http |
| 38 | + .get('http://localhost:3000/greet') |
| 39 | + .then((res) => (msg.value = res.data)) |
| 40 | + } |
| 41 | + const reset = () => { |
| 42 | + msg.value = 'Hello, Composition API!' |
| 43 | + } |
| 44 | + |
| 45 | + return { msg, getMsg1, getMsg2, reset } |
| 46 | + }, |
| 47 | + methods: { |
| 48 | + reset() { |
| 49 | + this.msg = 'Hello, World!' |
| 50 | + }, |
| 51 | + }, |
| 52 | + }) |
| 53 | + app.use(VueAxios, axios) |
| 54 | + app.provide('axios', app.config.globalProperties.axios) // provide 'axios' |
| 55 | + app.provide('$http', app.config.globalProperties.$http) // provide '$http' |
| 56 | + app.mount('#app') |
| 57 | + </script> |
| 58 | + </body> |
| 59 | +</html> |
0 commit comments