vue中使用axios模块加载数据

1.安装

 npm install axios

2.在main.js中引入

import Axios from 'axios'
Vue.prototype.$Axios=Axios

3.get请求

this.$Axios.get('http://jsonplaceholder.typicode.com/comments',{
                  params:{
                    postId:2,
                    t: Date.parse(new Date())  //请求时加入时间戳防止数据缓存
                  }
                })
                .then((respons)=>{            //要使用箭头函数,用function(){}时 this=undefined
                  console.log(respons.data); 
                })
                .catch((error)=>{
                  console.log(error);
                })

4.post请求

以form-data形式传参(只要用到qs库就行了,这个是axios中已经包含了的,不需要再下载相应的包了。)

import Qs from 'qs'
this.$Axios.post('http://jsonplaceholder.typicode.com/posts',
			Qs.stringify({
				userId: 11,
				id: 101,
				t: Date.parse(new Date())  //请求时加入时间戳防止数据缓存
			}),
			{headers: {'Content-Type':'application/x-www-form-urlencoded'}})
			.then((respons)=>{
				console.log(respons);
				this.object=respons.data;
			})
			.catch((error)=>{
				console.log(error);
			})

5.并发请求

function getUserAccount() {
  return axios.get('/user/12345',{params:{ t: Date.parse(new Date())}});
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions',{params:{ t: Date.parse(new Date())}});
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

6.跨域请求数据(只能在开发环境中使用)
1)修改config中index.js文件中的

  proxyTable: {
    '/api': {
        target: 'http://news-at.zhihu.com',//跨域访问的后端接口地址
        changeOrigin: true,//是否允许跨越
        pathRewrite: {
            '^/api': '',
        }
    }
  }

2)main.js中添加

  Vue.prototype.$url='/api' 

3)请求中写:

  var url=this.$url+"/api/4/news/latest";
  this.$Axios.get(url,{params:{ t: Date.parse(new Date())}})
              .then((respons)=>{
                  console.log(respons); 
              })
              .catch((error)=>{
                  console.log(error);
              })

7.vue使用axios时关于this的指向问题详解
https://www.jb51.net/article/131224.htm

如有疑惑移步axios中文网:https://www.kancloud.cn/yunye/axios/234845

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值