发送ajax请求

安装

在vue项目里面

  1. npm install axios

使用

在main.js里面,vue要先导入才行

  1. import axios from 'axios'
  2. Vue.prototype.$http = axios

在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $http命令

  1. methods: {
  2. postData () {
  3. this.$http({
  4. method: 'post',
  5. url: '/user',
  6. data: {
  7. name: 'xiaoming',
  8. info: '12'
  9. }
  10. })
  11. }

Get

直接拼接查询字符串

  1. $http.get('/user?ID=12345')
  2. .then(function (response) {
  3. console.log(response);
  4. })
  5. .catch(function (error) {
  6. console.log(error);
  7. });

/也可以通过 params 对象传递参数

  1. $http.get('/user', {
  2. params: {
  3. ID: 12345
  4. }
  5. })
  6. .then(function (response) {
  7. console.log(response);
  8. })
  9. .catch(function (error) {
  10. console.log(error);
  11. });

Post

  1. $http.post('/user', {
  2. firstName: 'Fred',
  3. lastName: 'Flintstone'
  4. })
  5. .then(function (response) {
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. console.log(error);
  10. });

执行多个请求

  1. function getUserAccount() {
  2. return $http.get('/user/12345');
  3. }
  4. function getUserPermissions() {
  5. return $http.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermissions()])
  8. .then($http.spread(function (acct, perms) {
  9. //两个请求现已完成
  10. }));

参考

vue2.0项目实战(3)使用axios发送请求
axios官方文档