vue 使用axios

官方地址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’即可
        }
      }
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值