Vue2.x Cli3.x vue-resource的安装和使用

安装vue-resource到项目中,找到当前项目

npm install vue-resource --save

安装完毕后,在main.js中导入,如下所示:

import VueResource from 'vue-resource'
Vue.use(VueResource)

get请求

fetchCustomers(){
      this.$http.get("http://localhost:3000/users")
        .then(function(response){
          // 响应成功回调
          // 打印获取到的数据
          console.log(response);
          // 把数据赋值给customers
          this.customers = response.body;
        }),function(response){
             // 响应错误回调
           }
}

post请求

this.$http.post("http://localhost:3000/users",newCustomer)
                    .then(function(response){
                        console.log(response);
                        this.$router.push({path:'/',query:{alert:"用户信息添加成功"}});
                    })

delete请求

deleteCustomer(id){
            this.$http.delete("http://localhost:3000/users/" + id)
                .then(function(response){
                    this.$router.push({path:'/',query:{alert:"数据删除成功!"}});
                })
            // console.log(id);
        }

put请求

this.$http.put("http://localhost:3000/users/" + this.$route.params.id,updataCustomer)
                    .then((response) =>{
                        console.log(response);
                        this.$router.push({path:'/',query:{alert:"用户信息更新成功"}});
                    })

简单查询

filterBy(customers,value){
      // filter、match为Es6中的语法
      return customers.filter(function(customer){
        return customer.name.match(value);
      })
    }
Last modification:June 7th, 2019 at 03:14 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment