vue-resource安装引入
方式一:终端安装
安装: npm i -D vue-resource
导入: import VueResource from 'vue-resource'
注册: Vue.(VueResource)
注:导入vue-resource时需要写在导入Vue的后面
方式二:标签引入
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
发送get请求
getInfo() { //发起get请求
// 第二步送请求,https://cn.vuejs.org/为请求地址,.then表示拿取数据里面可以写两个回调函数,第一个表示成功,第二个表示失败
this.$http.get("https://cn.vuejs.org/").then(function(result) {
console.log(result)
})
},
发送post请求
postInfo() { //发起post请求
// post请求需要表单模式,需要在第三个{}内用emulateJSON: true配置,手动发起的post没有表单模式,很多服务器无法处理
this.$http.post("https://jsonplaceholder.typicode.com/posts/", {}, {
emulateJSON: true
}).then(result => {
console.log(result.body)
})
}
发送jsonp请求
jsonpInfo() { //发起jsonp请求
this.$http.jsonp("http://jsonplaceholder.typicode.com/posts").then(function(result) {
console.log(result)
})
}
说明
1、使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。
2、如果使用便签引入的vue-resource,需要写在引入的vue文件下面