day02-vuejs-vue-resource实现get, p

2019-01-18  本文已影响20人  柠月如风z
vue-resource实现get, post, jsonp]请求:
JSONP的实现原理:

  1. vue-resource 的配置步骤:

项目:品牌列表的增删查项目
01.品牌列表-从数据库获取列表:

获取所有的品牌列表
分析:
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,可以弹框提醒,获取数据失败!

// 获取所有的品牌列表 
      getAllList() {
          this.$http.get('http://www.baidu.com').then(result => {
            if (result.status === 0) {
              // 成功了
              this.list = result.message
            } else {
              // 失败了
              alert('获取数据失败!')
            }
调用在data和methods之间:

当 vm 实例 的 data 和 methods 初始化完毕后,vm实例会自动执行created 这个生命周期函数

    created() { 
       this.getAllList()
      }
02.品牌列表-完成添加功能:

添加品牌列表到后台服务器
分析:
1. 听过查看 数据API接口,发现,要发送一个 Post 请求, this.http.post 2. this.http.post() 中接收三个参数:
2.1 第一个参数: 要请求的URL地址
2.2 第二个参数: 要提交给服务器的数据 ,要以对象形式提交给服务器 { name: this.name }
3.3 第三个参数: 是一个配置对象,要以哪种表单数据类型提交过去, { emulateJSON: true }, 以普通表单格式,将数据提交给服务器 application/x-www-form-urlencoded
3. 在 post 方法中,使用 .then 来设置成功的回调函

add(){
this.$http.post('api/addproduct', { name: this.name }, { emulateJSON: true }).then(result => {
            if (result.body.status === 0) {
              // 成功了!
              // 添加完成后,只需要手动,再调用一下 getAllList 就能刷新品牌列表了
              this.getAllList()
              // 清空 name 
              this.name = ''
            } else {
              // 失败了
              alert('添加失败!')
            }
          }) 
}
03.品牌列表-完成删除功能:
 del(id) { // 删除品牌
          this.$http.get('api/delproduct/' + id).then(result => {
            if (result.body.status === 0) {
              // 删除成功
              this.getAllList()
            } else {
              alert('删除失败!')
            }
          })
        }
04.品牌列表-全局配置数据接口的根域名与全局启用 emulateJSON 选项:

注意:程序应写在创建实例对象之前
如果我们通过全局配置了,请求的数据接口 根域名,则 ,在每次单独发起 http 请求的时候,请求的 url 路径,应该以相对路径开头,前面不能带 / ,否则 不会启用根路径做拼接;

 Vue.http.options.root = 'http://xxxx';
全局启用 emulateJSON 选项:
Vue.http.options.emulateJSON = true;
上一篇 下一篇

猜你喜欢

热点阅读