Vue 中使用Ajax请求

Vue 项目中常用的 2 个 ajax 库

(一)vue-resource

vue 插件, 非官方库,vue1.x 使用广泛

vue-resource 的使用

在线文档   https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

下载

npm install vue-resource --save

编码

// 引入模块 ,注意应该在入口文件main.js中引入和声明

import VueResource from 'vue-resource'

// 声明使用

Vue.use(VueResource)  //内部会给vm对象和组件对象添加一个属性:$http

// 通过 vue组件对象发送 ajax 请求(发送get请求)

this.$http.get('/someUrl?foo=bar').then(

response=>{//successcallback

console.log(response.data)//返回结果数据

},

response=>{//errorcallback

console.log(response.statusText)//错误信息
})

 // 通过 vue组件对象发送 ajax 请求(发送post请求)

this.$http.post('/someUrl', {foo: 'bar'}).then(

response=>{//successcallback

console.log(response.data)//返回结果数据

},

response=>{//errorcallback

console.log(response.statusText)//错误信息
})

 

(二)axios

通用的 ajax 请求库, 官方推荐,vue2.x 使用广泛

axios 的使用

在线文档   https://github.com/axios/axios/blob/master/README.md

下载

npm install axios --save

编码

// 引入模块,无需声明,在组件中引入

import axios from 'axios'
// 发送 ajax 请求(发送get请求)

axios.get('/someUrl?foo=bar') .then(   

response=>{//successcallback

console.log(response.data)// 得到返回结果数据

}) .catch(

error=>{

console.log(error.message)//错误信息

})

// 发送 ajax 请求(发送post请求)

axios.post('/someUrl', {foo'bar'}) .then(   

response=>{//successcallback

console.log(response.data)// 得到返回结果数据

}) .catch(

error=>{

console.log(error.message)//错误信息

})

转载于:https://www.cnblogs.com/adongyo/p/11260943.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值