>[success] # 使用vue-resource 包进行异步 ## [vue-resource 实现 get, post, jsonp请求](https://github.com/pagekit/vue-resource) ~~~ 1.配置resource全局配置了,请求的数据接口 根域名 Vue.http.options.root = 'http://vue.studyit.io/'; 2.全局启用 emulateJSON 选项Vue.http.options.emulateJSON = true;,就是当post 的时候不用在添加第三个参数 ~~~ * 获取所有数据分析思路 ~~~ 1. 由于已经导入了 Vue-resource这个包,所以 ,可以直接通过 this.$http 来 发起数据请求 2. 根据接口API文档,知道,获取列表的时候,应该发起一个 get 请求 3. this.$http.get('url').then(function(result){}) 4. 当通过 then 指定回调函数之后,在回调函数中,可以拿到数据服务器返回的 result 5. 先判断 result.status 是否等于0,如果等于0,就成功了,可以 把 result.message 赋值给 this.list ; 如果不等于0,可以弹框提醒,获取数据失败! ~~~ * 添加数据分析思路 ~~~ 1. 听过查看 数据API接口,发现,要发送一个 Post 请求, this.$http.post 2. this.$http.post() 中接收三个参数: 2.1 第一个参数: 要请求的URL地址 2.2 第二个参数: 要提交给服务器的数据 ,要以对象形式提交给服务器 { name: this.name } 2.3 第三个参数: 是一个配置对象,要以哪种表单数据类型提交过去, { emulateJSON: true }, 以普通表单格式,将数据提交给服务器 application/x-www-form-urlencoded 3. 在 post 方法中,使用 .then 来设置成功的回调函数,如果想要拿到成功的结果,需要 result.body ~~~ >[danger] ##### 案例 ~~~ <script src="./lib/vue-2.4.0.js"></script> <!-- 注意:vue-resource 依赖于 Vue,所以先后顺序要注意 --> <!-- this.$http.jsonp --> <script src="./lib/vue-resource-1.3.4.js"></script> </head> <body> <div id="app"> <input type="button" value="get请求" @click="getInfo"> <input type="button" value="post请求" @click="postInfo"> <input type="button" value="jsonp请求" @click="jsonpInfo"> </div> <script> // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: { getInfo() { // 发起get请求 // 当发起get请求之后, 通过 .then 来设置成功的回调函数 this.$http.get('http://vue.studyit.io/api/getlunbo').then(function (result) { // 通过 result.body 拿到服务器返回的成功的数据 // console.log(result.body) }) }, postInfo() { // 发起 post 请求 application/x-wwww-form-urlencoded // 手动发起的 Post 请求,默认没有表单格式,所以,有的服务器处理不了 // 通过 post 方法的第三个参数, { emulateJSON: true } 设置 提交的内容类型 为 普通表单数据格式 this.$http.post('http://vue.studyit.io/api/post', {}, { emulateJSON: true }).then(result => { console.log(result.body) }) }, jsonpInfo() { // 发起JSONP 请求 this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result => { console.log(result.body) }) } } }); </script> </body> </html> ~~~ >[danger] ##### 使用axios -- 基于promise 封装的库 ~~~ 1.去看文档就能学会这个 ~~~