谈谈Vue.js——vue-resource全攻略

2020-06-16 06:04:52易采站长站整理

vm.$set('item', {})
vm.getCustomers()
})
this.show = false
}
}
})

 PUT请求


updateCustomer: function() {
var vm = this
vm.$http.put(this.apiUrl + '/' + vm.item.customerId, vm.item)
.then((response) => {
vm.getCustomers()
})
}

 

Delete请求


deleteCustomer: function(customer){
var vm = this
vm.$http.delete(this.apiUrl + '/' + customer.customerId)
.then((response) => {
vm.getCustomers()
})
}

使用resource服务

vue-resource提供了另外一种方式访问HTTP——resource服务,resource服务包含以下几种默认的action:


get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}

resource对象也有两种访问方式:

全局访问:Vue.resource
实例访问:this.$resource

resource可以结合URI Template一起使用,以下示例的apiUrl都设置为{/id}了:

apiUrl: ‘http://211.149.193.19:8080/api/customers{/id}’

GET请求

使用get方法发送GET请求,下面这个请求没有指定{/id}。


getCustomers: function() {

var resource = this.$resource(this.apiUrl)
vm = this

resource.get()
.then((response) => {
vm.$set('gridData', response.data)
})
.catch(function(response) {
console.log(response)
})
}

POST请求

使用save方法发送POST请求,下面这个请求没有指定{/id}。


createCustomer: function() {
var resource = this.$resource(this.apiUrl)
vm = this

resource.save(vm.apiUrl, vm.item)
.then((response) => {
vm.$set('item', {})
vm.getCustomers()
})
this.show = false
}

 PUT请求

使用update方法发送PUT请求,下面这个请求指定了{/id}。


updateCustomer: function() {
var resource = this.$resource(this.apiUrl)