如何从Vue.js应用中与API互动
很多开发者使用JavaScript构建应用程序,这就构成了一个事实,即大多数Web应用程序都将JavaScript作为其主要编程语言之一。构建JavaScript框架是为了让开发者的开发过程更简单、更快速。Vue.js是许多流行的JavaScript框架之一。其他框架包括React和Angular。
什么是Vue.js
Vue.js是一个渐进式的JavaScript框架,用于开发交互式用户界面。Vue.js被称为渐进式框架,因为它对用户友好,可以很容易地与不同的框架或库合并。
在使用Vue.js开发大多数项目时,会需要从API中获取或消耗数据。这是用来使前端与应用程序的后端互动的。获取的数据然后可以在应用程序的前端消费。
什么是API?
API是应用编程接口的意思,它是一套允许应用程序共享数据的协议。它更像是一个软件中介。要在Vue.js中使用API,你必须使用这些方法中的任何一种来发出API请求。Axios或Fetch方法。
这些概念将在本文中得到广泛的讨论。
前提条件
为了理解和学习这篇文章,你应该有。
- 在你的电脑上安装了Node.js。
- 在你的电脑上安装了Vue.js。
- 理解Vue.js中的关键概念。
概述
- 使用Axios来消费一个API
- 使用Fetch API方法
- 在Vuex中使用API
- 总结
使用Axios来消费API
Axios是一个基于承诺的HTTP客户端,这使得它适合在服务器端显示时获取数据。它在浏览器和Node应用中都能工作。Axios是一个围绕Fetch API构建的库。
Axios的安装
要在你的项目中使用Axios,你应该安装它。这可以通过两种方式完成。
-
通过使用
npm:一个用于JavaScript运行环境Node.js的标准包管理器。你现在可以明白为什么在你的电脑上安装Node.js是一个先决条件。 -
通过使用
yarn:它是一个软件包管理器,同时也充当了项目管理器。它与npm注册表是同步的,具有相同的功能。要在你的项目中安装yarn,在你的终端粘贴以下一行代码npm install --global yarn
用npm。
npm i axios
用yarn。
yarn add axios
接下来,你应该在你的src/main.js 文件中导入Axios
import axios from 'axios';
Vue.prototype.$http = axios;
如何使用Axios进行API请求并显示数据
现在,我们将使用GET 方法发出我们的第一个API请求。GET方法是用来从API中获取数据的。我们希望这个API请求是异步运行的,因此,我们使用一个基于承诺的函数,其关键字为async/await。
你可能想知道为什么我们要使用一个基于承诺的函数。这是因为诺言是一个代名词,在创建诺言的时候不一定知道它的值。由于API请求需要不确定的时间,所以我们使用承诺。
我们还需要使用try/catch方法来测试错误。try ,用于检查错误,而catch ,用于在错误发生时处理错误。
复制下面的代码到你的App.vue 文件。
<template></template>
<script>
export default {
data() {
return {
posts: [],
};
},
methods: {
async getData() {
try {
const response = await this.$http.get(
"http://jsonplaceholder.typicode.com/posts"
);
// JSON responses are automatically parsed.
this.posts = response.data;
} catch (error) {
console.log(error);
}
},
},
};
</script>
上述methods 属性中的代码块将被逐行解释。
async getData (){
这里创建了一个名为getData() 的函数。在这个函数中,API将被调用。async 关键字被预置在getData 函数上,以表明该函数将利用承诺,我们将使用它来等待,以暂停函数的执行,直到承诺被解决。
try {
const response = await this.$http.get('http://jsonplaceholder.typicode.com/posts');
try 属性定义了一个代码块,在代码执行过程中进行错误测试。在代码块 ,使用axios即 ,用 关键字发出一个获取请求,从URL获取数据。const response = await this.$http.get('http://jsonplaceholder.typicode.com/posts');``$http get
await 因为 函数将返回一个承诺,所以在请求中预留了 "承诺"。承诺后从API返回的数据被解析,并将被存储在变量 。get response
this.posts = response.data
我们从请求中得到的数据然后被保存到posts 数组中,该数组在数据属性中被创建。
catch (error) {
console.log(error);
}
如果在执行过程中发生任何错误,错误将被捕获并记录在控制台中。
从API请求数据后,你需要在一个生命周期钩子上调用它。这里我们将使用created() 生命周期钩子,这是因为我们将能够检索敏感的数据和事件,这些数据和事件是通过created 钩子活动的。
<template></template>
<script>
export default {
data() {
return {
posts: [],
};
},
methods: {
async getData() {
try {
const response = await this.$http.get(
"http://jsonplaceholder.typicode.com/posts"
);
// JSON responses are automatically parsed.
this.posts = response.data;
console.log(posts);
} catch (error) {
console.log(error);
}
},
},
created() {
this.getData();
},
};
</script>
现在我们可以通过使用v-for指令循环浏览帖子来显示模板中的数据。
<template>
<div>
<div v-for="post in posts" v-bind:key="post.id">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
posts: [],
};
},
methods: {
async getData() {
try {
const response = await this.$http.get(
"http://jsonplaceholder.typicode.com/posts"
);
this.posts = response.data;
} catch (error) {
console.log(error);
}
},
},
created() {
this.getData();
},
};
</script>
使用Fetch API方法
Fetch API是一个强大而灵活的灵活API方法。它产生了一个全局的fetch()方法,提供了一个简单合理的方法来通过网络异步获取资源。
要用Fetch API请求,你只需要直接用fetch 对象进行请求,并遵循上述Axios调用中使用的所有其他步骤。
<template>
<div>
<ul v-for="post in posts" v-bind:key="post.id">
<li>{{ post.title }}</li>
<p>{{ post.body }}</p>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
posts: [],
};
},
methods: {
async getData() {
try {
let response = await fetch("http://jsonplaceholder.typicode.com/posts");
this.posts = await response.json();;
} catch (error) {
console.log(error);
}
},
},
created() {
this.getData();
},
};
</script>
在Vuex中创建API
Vuex是Vue.js应用程序的一个状态管理库。它为应用程序中的所有元素提供了一个集中的存储。
安装Vuex
为了使用Vuex,你首先需要在你的Vue应用程序上安装Vuex包。
vue create project
或
npm install vuex --save
然后,在你的store 文件夹中,访问index.js 文件并编写以下代码
import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";
Vue.use(Vuex);
进行API请求
我们将使用store/index.js 文件。首先,我们创建一个state 对象,它将包含所有应用程序级别的状态。它可以作为vuex项目中存储的data 对象。
export default new Vuex.Store({
state: {
posts: [],
},
})
接下来,我们创建一个getters 属性。Getters就像商店的computed 属性。它被用来确定基于商店状态的派生状态。在本教程中,我们将用它来返回状态中的帖子。
getters: {
posts: state => {
return state.posts;
}
},
接下来,我们创建一个mutation 属性。突变属性是我们可以改变Vuex商店中的状态的地方。有非常类似于我们进行实际状态改变的事件。
mutations: {
SET_ITEMS (state, posts) {
state.posts = posts
}
},
现在我们可以在actions 属性中调用我们的API。行动等同于突变,只是行动提交突变而不是突变状态,而且行动可以进行异步操作。让我们继续进行API调用。
actions: {
async loadPosts ({ commit }) {
try {
const response = await this.$http.get('http://jsonplaceholder.typicode.com/posts');
// JSON responses are automatically parsed.
commit('SET_ITEMS', response.data)
}
catch (error) {
console.log(error);
}
}
},
现在,我们应该在src/main.js 中导入商店,并将其传递给我们的Vue应用程序。
import store from "../store/index";
new Vue({
render: (h) => h(App),
store,
}).$mount("#app");
现在,我们可以在我们的vue文件中显示这些数据。要做到这一点,需要采取一些步骤。
- 使用
computed属性,我们访问商店中getters方法的内容。
<script>
export default {
computed: {
posts() {
return this.$store.getters.posts;
},
},
- 在一个生命周期钩子上调用API
created,并采用dispatch方法来调用动作。
created() {
this.$store.dispatch('loadPosts');
},
}
</script>
- 最后在你的模板上显示数据。
<template>
<div>
<div v-for="post in posts" v-bind:key="post.id">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
下面是整个代码片断。
对于store 文件。
import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
posts: [],
},
getters: {
posts: state => {
return state.posts;
}
},
mutations: {
SET_ITEMS (state, posts) {
state.posts = posts
}
},
actions: {
async loadPosts ({ commit }) {
try {
const response = await axios.get('http://jsonplaceholder.typicode.com/posts');
commit('SET_ITEMS', response.data)
}
catch (error) {
console.log(error);
}
}
},
})
对于你的Vue文件。
<template>
<div>
<div v-for="post in posts" v-bind:key="post.id">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
<script>
export default {
computed: {
posts() {
return this.$store.getters.posts;
},
},
created() {
this.$store.dispatch('loadPosts');
},
}
</script>
结论
在本教程中,我们已经研究了在Vue.js项目中与API交互的两种方法。这两种与API交互的方法在很多方面都很相似,都能完成工作。然而,建议使用Axios来处理更复杂的请求,因为它允许在一个地方对多个请求进行许多配置。
我们还考虑了在Vuex项目中消费API,即管理多个状态的项目。
我希望这篇文章对你有很大的帮助 🙂.