npm安装axios和vue-axios
npm install axios --save
npm install --save vue-axios
vue配置文件:在根目录新建:vue.config.js
module.exports = {
outputDir: 'dist', //build输出目录
assetsDir: 'assets', //静态资源目录(js, css, img)
lintOnSave: false, //是否开启eslint
devServer: {
open: true, //是否自动弹出浏览器页面
host: "localhost",
port: '8081',
https: false, //是否使用https协议
hotOnly: false, //是否开启热更新
proxy: {
'/api': {
target: 'http://127.0.0.1:8000/api', //API服务器的地址
ws: true, //代理websockets
changeOrigin: true, // 虚拟的站点需要更管origin
pathRewrite: { //重写路径 比如'/api/aaa/ccc'重写为'/aaa/ccc'
'^/api': ''
}
}
},
}
}
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
Vue.config.productionTip = false
Vue.prototype.$axios=axios;
new Vue({
router,
render: h => h(App)
}).$mount('#app')
请求本地数据:
服务器是用Django提供的api:
在Vue项目:components/User.vue中请求Django的api:
<template>
<div id="User">
{{ page_info }}
</div>
</template>
<script>
export default{
name:"User",
data(){
return{
page_info:"this User page"
}
},
created(){
this.$axios.get("/api/test/")
.then(response => {
console.log(response.data)
},)
}
}
</script>
<style>
</style>
请求结果: