官方地址https://www.npmjs.com/package/vue-axios
安装axios插件
vscode的TERMINAL中,在项目目录下输入
npm install --save axios vue-axios
全局引入
main.js增加
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
官方给出的几种形式
Vue.axios.get(api).then((response) => {
console.log(response.data)
})
this.axios.get(api).then((response) => {
console.log(response.data)
})
this.$http.get(api).then((response) => {
console.log(response.data)
})
本人测试
在需要的地方增加请求
<script>
export default {
//你的逻辑代码块
...
xxxxxxx
...
this.axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(err)
})
}
</script>
post
this.axios.post('/user',{
name:'bob',
age:'22'
})
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});
跨域请求
编辑config/index.js
proxyTable: {
'/api': {
target: 'http://localhost:8001',//跨域地址,接口地址
changeOrigin: true,
pathRewrite: {
'^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://localhost:8001/add',直接写‘/api/add’即可
}
}
},