4.7.作为vue的插件使用
在vue中,我们不需要在每个组件中都去引入axios,这样使用起来比较麻烦,我们可以结合插件vue-axios,让操作更简化
1.安装插件
npm install vue-axios --save
2.在入口文件中引入模块,并挂载插件
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import '@/assets/style/index.css'
import store from '@/store/index'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
3.在组件中使用axios
<template>
<div class="page">
</div>
</template>
<script type="text/javascript">
export default {
data () {
return {
}
},
components: {
},
created () {
function http1 () {
return this.axios.get('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list')
}
function http2 () {
return this.axios.post('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/update')
}
this.$http.all([http1.bind(this), http2.bind(this)]).then(this.axios.spread((res1, res2) => {
// res1 对应http1的请求结果 res2对应http2的请求结果
console.log(res1, res2)
}))
this.axios.get('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list').then((response) => {
console.log(response)
})
this.$http.get('https://easy-mock.com/mock/5c23887d3671d47be5ea8d66/axiosdemo/course/list').then((response) => {
console.log(response)
})
}
}
</script>
<style scoped>
</style>
网友评论