如何使用 Axios 配置 Vue.js REST API 用量

介绍

在Vue 2.0中,开发人员决定拥有内置的HTTP客户端模块是相当多余的,可以更好地由第三方库提供服务。

Axios是一个HTTP客户端库. 它默认使用承诺,并在客户端和服务器上运行,这使得它适合在服务器端渲染过程中获取数据。

在本文中,您将探索如何将 Axios 添加到 Vue.js 项目中,以执行涉及填充数据和推送数据的任务,您还将了解如何创建可重复使用的数据库实例。

前提条件

要跟随这篇文章,你将需要:

安装和导入axios

首先,你需要安装 Axios。

您可以使用 npm 安装 Axios:

1npm install axios --save

或者用铁:

1yarn add axios

当您将 Axios 添加到 Vue.js 项目时,您将想要导入:

1import axios from 'axios';

接下来,我们将使用axios.get()来执行GET请求。

填充GET请求的数据

您可以直接在您的组件中使用 Axios 来从方法或生命周期链接中获取数据:

 1[label ExampleComponentGet.vue]
 2<template>
 3  <div>
 4    <ul v-if="posts && posts.length">
 5      <li v-for="post of posts">
 6        <p><strong>{{post.title}}</strong></p>
 7        <p>{{post.body}}</p>
 8      </li>
 9    </ul>
10
11    <ul v-if="errors && errors.length">
12      <li v-for="error of errors">
13        {{error.message}}
14      </li>
15    </ul>
16  </div>
17</template>
18
19<script>
20import axios from 'axios';
21
22export default {
23  data() {
24    return {
25      posts: [],
26      errors: []
27    }
28  },
29
30  // Fetches posts when the component is created.
31  created() {
32    axios.get(`http://jsonplaceholder.typicode.com/posts`)
33    .then(response => {
34      // JSON responses are automatically parsed.
35      this.posts = response.data
36    })
37    .catch(e => {
38      this.errors.push(e)
39    })
40  }
41}
42</script>

async / Wait 版本将看起来像这样:

 1[label ExampleComponentGet.vue]
 2<!-- ... template code ... -->
 3
 4<script>
 5import axios from 'axios';
 6
 7export default {
 8  data() {
 9    return {
10      posts: [],
11      errors: []
12    }
13  },
14
15  // Fetches posts when the component is created.
16  async created() {
17    try {
18      const response = await axios.get(`http://jsonplaceholder.typicode.com/posts`)
19      this.posts = response.data
20    } catch (e) {
21      this.errors.push(e)
22    }
23  }
24}
25</script>

此代码将从 JSONPlaceholder 获取``帖子并填充一个未分类的列表,其中包含帖子`。

接下来,我们将使用axios.post()来执行POST请求。

通过POST请求推送数据

您可以使用 Axios 发送POST,PUT,PATCHDELETE请求。

<$>[注] **注:**您不希望在每个输入事件上发送请求。

 1[label ExampleComponentPost.vue]
 2<template>
 3  <div>
 4    <input type="text" v-model="postBody" @change="postPost()" />
 5    <ul v-if="errors && errors.length">
 6      <li v-for="error of errors">
 7        {{error.message}}
 8      </li>
 9    </ul>
10  </div>
11</template>
12
13<script>
14import axios from 'axios';
15
16export default {
17  data() {
18    return {
19      postBody: '',
20      errors: []
21    }
22  },
23
24  methods: {
25    // Pushes posts to the server when called.
26    postPost() {
27      axios.post(`http://jsonplaceholder.typicode.com/posts`, {
28        body: this.postBody
29      })
30      .then(response => {})
31      .catch(e => {
32        this.errors.push(e)
33      })
34    }
35  }
36}
37</script>

async / Wait 版本将看起来像这样:

 1[label ExampleComponentPost.vue]
 2<!-- ... template code ... -->
 3
 4<script>
 5import axios from 'axios';
 6
 7export default {
 8  data() {
 9    return {
10      postBody: '',
11      errors: []
12    }
13  },
14
15  methods: {
16    // Pushes posts to the server when called.
17    async postPost() {
18      try {
19        await axios.post(`http://jsonplaceholder.typicode.com/posts`, {
20          body: this.postBody
21        })
22      } catch (e) {
23        this.errors.push(e)
24      }
25    }
26  }
27}
28</script>

此代码会创建一个输入字段,将内容提交到 JSONPlaceholder

接下来,我们将使用axios.create()来创建一个基础实例。

创建一个共同的基础实例

Axios 提供的一项常被忽视但非常有用的功能是创建一个基本实例,允许您在所有呼叫实例中共享一个共同的基本 URL 和配置。

1[label http-common.js]
2import axios from 'axios';
3
4export const HTTP = axios.create({
5  baseURL: `http://jsonplaceholder.typicode.com/`,
6  headers: {
7    Authorization: 'Bearer {token}'
8  }
9})

您现在可以在您的组件中使用HTTP:

 1[label ExampleComponentBase.vue]
 2<template>
 3  <div>
 4    <ul v-if="posts && posts.length">
 5      <li v-for="post of posts">
 6        <p><strong>{{post.title}}</strong></p>
 7        <p>{{post.body}}</p>
 8      </li>
 9    </ul>
10
11    <ul v-if="errors && errors.length">
12      <li v-for="error of errors">
13        {{error.message}}
14      </li>
15    </ul>
16  </div>
17</template>
18
19<script>
20import { HTTP } from './http-common';
21
22export default {
23  data() {
24    return {
25      posts: [],
26      errors: []
27    }
28  },
29
30  created() {
31    HTTP.get(`posts`)
32    .then(response => {
33      this.posts = response.data
34    })
35    .catch(e => {
36      this.errors.push(e)
37    })
38  }
39}
40</script>

此代码使用了在http-common.js中设置的配置,并通过授权标题连接到JSONPlaceholder,检索帖子并捕获任何错误。

结论

在本文中,您介绍了如何使用 Axios 来填充数据和推送数据,以及如何创建可重复使用的基例。

请访问 GitHub 存储库以获取有关 Axios 的更多信息和文档。

如果您想了解有关 Vue.js 的更多信息,请参阅 我们的 Vue.js 主题页面以获取练习和编程项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus