1.使用npm i axios --save
2.全局使用 main.js中
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { showMixin } from './mixins/index'
// import axios from 'vue-axios'
import axios from 'axios'
// import VueCompositionApi from '@vue/composition-api'
// createApp(App).config.productionTip = false
// createApp(App).use(store).use(router).use(VueCompositionApi).mount('#app')
// =========配置minxin
// createApp(App).mixin(showMixin).use(store).use(router).mount('#app')
// ===========配置axios
const app = createApp(App)
axios.defaults.baseURL = 'http://www.kymid.com/testphp/public/index.php/api/'
app.config.globalProperties.$http = axios
app.mixin(showMixin).use(store).use(router).mount('#app')
3.在组件中使用
<template>
<div class="about">
<h1>This is an about page</h1>
<button @click="mymixin">测试mixin</button>
<button @click="fn">测试mixin</button>
</div>
</template>
<script>
// import { showMixin } from '../mixins/index'
// export default {
// mixins: [showMixin]
// }
export default {
created () {
// this.$http.get('http://www.kymid.com/testphp/public/index.php/api/apis/about_get?lang=en').then(val => {
this.$http.get('apis/about_get?lang=en').then(val => {
console.log(val)
})
}
}
</script>
方法二:在vue3中,新的组合式[API]没有this,那我们如果需要用到this
怎么办?
getCurrentInstance 方法获取当前组件的实例,然后通过 ctx
或 proxy
属性获得当前上下文,这样我们就能在setup中使用router和vuex了
import { getCurrentInstance, onMounted } from 'vue'
setup (props, context) {
// 在
const { proxy } = getCurrentInstance()
onMounted(() => {
getData()
})
function getData () {
proxy.$http.get('apis/about_get?lang=en').then(res => {
console.log(res)
})
}
}
方法三:使用provide 和 inject 方法共享
main.js中:
const app = createApp(App)
axios.defaults.baseURL = 'http://www.kymid.com/testphp/public/index.php/api/'
app.config.globalProperties.$http = axios
// 方法三:
app.provide('$axios', axios)
组件中:
import { getCurrentInstance, onMounted, inject } from 'vue'
// import { inject } from 'vue'
export default {
created () {
// 方式一: 在created中 直接使用this调用
// this.$http.get('http://www.kymid.com/testphp/public/index.php/api/apis/about_get?lang=en').then(val => {
this.$http.get('apis/about_get?lang=en').then(val => {
console.log(val)
})
},
setup (props, context) {
// 在
const { proxy } = getCurrentInstance()
onMounted(() => {
getData()
})
function getData () {
proxy.$http.get('apis/about_get?lang=en').then(res => {
console.log(res)
})
}
// 方法三: 使用共享
const $axios = inject('$axios')
$axios.get('apis/about_get?lang=en').then((resp) => {
console.log(resp)
})
}
}