Vue.js Ajax(vue-resource)学习笔记
在 Vue.js 中,我们可以通过 vue-resource
进行 AJAX 请求。vue-resource
是一个 Vue.js 的插件,提供了方便的 $http
方法来进行 AJAX 请求。
安装
在使用 vue-resource
前,需要先安装它:
bashCopy Codenpm install vue-resource --save
安装完成后,在项目中引入 vue-resource
:
javascriptCopy Codeimport Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)
发送 GET 请求
使用 $http.get
方法可以发送 GET 请求。例如:
javascriptCopy Codethis.$http.get('/api/users').then(response => {
console.log(response.body)
})
上面的代码会向 /api/users
发送 GET 请求,并在返回结果后打印响应体(即服务器返回的数据)。
发送 POST 请求
使用 $http.post
方法可以发送 POST 请求。例如:
javascriptCopy Codethis.$http.post('/api/users', { name: 'John', age: 30 }).then(response => {
console.log(response.body)
})
上面的代码会向 /api/users
发送 POST 请求,并把 { name: 'John', age: 30 }
作为请求体发送给服务器。在返回结果后打印响应体。
发送 PUT 请求
使用 $http.put
方法可以发送 PUT 请求。例如:
javascriptCopy Codethis.$http.put('/api/users/1', { name: 'John', age: 31 }).then(response => {
console.log(response.body)
})
上面的代码会向 /api/users/1
发送 PUT 请求,并把 { name: 'John', age: 31 }
作为请求体发送给服务器。在返回结果后打印响应
[Something went wrong, please try again later.]