用JSON服务器和Axios构建Vue 3应用程序

222 阅读4分钟

在靠近用户的地方部署容器

本工程教育(EngEd)计划由科支持。

在全球范围内即时部署容器。Section是经济实惠、简单而强大的。

免费开始

用JSON服务器和Axios构建Vue 3应用程序

2022年1月2日

Vue是一个前端JavaScript框架,用于创建运行在客户端的单页应用程序。它也可以通过向后端服务器发出HTTP请求来创建全栈应用。它与Node.js和Express(MEVN栈)一起流行。

JSON服务器是一个npm包,可以让你用零编码创建模拟的REST API。它用于创建一个简单的JSON文件,可以作为数据库使用,并响应HTTP请求。

Axios是HTTP客户端,我们将用它来向JSON服务器发出HTTP请求。

在这篇文章中,我们将建立一个购物清单应用程序。我们将从一个空白的Vue.js应用程序开始,然后添加用于本地数据存储的JSON服务器,以及用于发出HTTP请求的Axios。

shopping-list

目录

先决条件

要继续学习本教程,你需要具备以下条件。

  • 安装了Node.js
  • 一些JavaScript知识。

创建一个新的Vue.js应用程序

假设你已经在电脑上安装了Node,在终端运行以下命令来安装Vue CLI。

$ npm install -g @vue/cli

安装完成后,使用创建一个新项目。

$ vue create shopping-list 

导航到shopping-list 文件夹,在你喜欢的代码编辑器中打开该项目。如果你使用的是VS Code,运行以下命令在VS Code中打开项目。

$ cd shopping-list
$ code .

然后运行下面的命令来启动Vue.js应用程序。

$ npm run serve

该应用程序将在浏览器中运行http://localhost:8080/ 。现在你应该看到默认的Vue主页在你的浏览器中运行。

设置JSON服务器

现在让我们创建一个简单的JSON文件,作为一个数据库使用。

在我们的shopping-list 目录中,创建一个名为data.json 的文件。

$ touch data.json

让我们在该文件中添加以下数据。

{
  "items":[
      {
      "id":0,
      "name":"Carrots"
      },
      {
      "id":1,
      "name":"Cabbage"
      },
      {
      "id":2,
      "name":"Banana"
      },
      {
      "id":0,
      "name":"Cakes"
      }
  ]
}

我们已经创建了一个购物清单对象,其中包含一个物品清单以及它们的ID。为了在我们的应用程序中使用这些数据,我们需要使用json-server 。运行下面的命令来安装该软件包。

# Install json-server globally
$ npm install json-server -g 
$ json-server data.json

命令json-server 将使用我们data.json 文件中的数据启动一个服务器。

默认情况下,服务器运行在localhost 3000端口。如果你在浏览器中导航到http://localhost:3000/items ,你应该得到服务器的JSON响应。

在我们的应用程序中获取HTTP数据

为了访问我们应用程序中的数据,我们需要使用HTTP客户端Axios

让我们来安装这个包。

$ npm install axios

安装完成后,我们现在可以在我们的应用程序中导入axios

在我们的App.vue ,让我们删除模板、脚本和样式标签内的所有内容。添加以下代码。

<template>
  <div id="app">
    <h1>Shopping List</h1>
  </div>
  <ul>
    <li v-for="item of items" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
</template>
<script>
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      items: [],
    };
  },
  async created() {
    try {
      const res = await axios.get(`http://localhost:3000/items`);
      this.items = res.data;
    } catch (error) {
      console.log(error);
    }
  },
};
</script>
<style>
#app {
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
li {
  list-style: none;
}
</style>

我们来解释一下上面的代码。

import axios from "axios";

在这里,我们已经导入了Axios,它将帮助我们访问data.json 文件中的数据。

我们利用了async和await机制,它建立在承诺的基础上,允许你构建异步代码。

async created() {
    // ...
}

在这里,我们使用了created() 钩子,它将用于从后端API获取数据并将其设置为数据属性。async 关键字是在created() 函数的前面,表明该函数将使用承诺,我们将使用它来等待和暂停执行,直到来自服务器的数据被解决。

try {
   const res = await axios.get(`http://localhost:3000/items`);
}

我们使用了try/catch 块来捕捉错误。try 块用于从服务器获取数据,而catch 则用于处理错误(如果发生错误)。

使用POST请求添加数据

你可以使用Axios向数据库发出POSTPUTPATCHDELETE 请求。

POST 是一种HTTP方法,用于创建或添加数据到数据库。在我们的方法中,让我们添加 函数,向我们的购物清单添加一个项目。addItem

<template>
  <div id="app">
    <h1>Shopping List</h1>
    <input v-model="itemName" type="text" /><br />
    <button @click="addItem()">Add Item</button>
  </div>
  <ul>
    <li v-for="item of items" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
</template>
<script>
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      items: [],
      itemName: "",
    };
  },
  async created() {
    try {
      const res = await axios.get(`http://localhost:3000/items`);
      this.items = res.data;
    } catch (error) {
      console.log(error);
    }
  },
  methods: {
    async addItem() {
      const res = await axios.post(`http://localhost:3000/items`, {
        name: this.itemName,
      });
      this.items = [...this.items, res.data];
      this.itemName = "";
    },
  },
};
</script>

adding input area and a button

在这里,我们已经添加了一个输入区和一个按钮。我们还添加了addItem() 方法,一旦你点击按钮添加项目,就会调用该方法。JSON服务器通过自动增加1来处理id 这个属性。然后我们将新的项目设置为包含每个项目元素,然后将项目添加到列表的最后。

使用PATCH请求更新数据

我们可以使用PATCH 方法来更新一个对象中的一个值。我们将通过在我们的方法中添加以下函数来剔除我们已经购买的物品。

async boughtItem(id) {
    try {
        await axios.patch(`${`http://localhost:3000/items`}/${id}`, {
            boughtItem: true
        });
        this.items = this.items.map(item => {
            if (item.id === id) {
                item.boughtItem = true;
            }
            return item;
        });
    } catch (error) {
        console.error(error);
    }
}

使用DELETE请求删除数据

DELETE 方法是一个用于删除HTTP服务器中特定数据的请求。

我们可以通过在我们的方法中添加以下函数来增加删除功能。

removeItem(id) {
    axios.delete(`http://localhost:3000/items/${id}`)
    this.items = this.items.filter(item => item.id !== id)
}

在我们的App.vue ,添加这两个方法后,我们应该有以下代码。

<template>
  <div class="container">
    <div id="app">
      <h1>Shopping List</h1>
      <input v-model="itemName" @keyup.enter="addItem" type="text" /><br />
      <button @click="addItem()">Add Item</button>
    </div>
    <ul>
      <li
        v-for="item of items"
        :class="{ bought: item.bought }"
        :key="item.id"
        @click="boughtItem(item.id)"
        @dblclick="removeItem(item.id)"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      items: [],
      itemName: "",
    };
  },
  async created() {
    try {
      const res = await axios.get(`http://localhost:3000/items`);
      this.items = res.data;
    } catch (error) {
      console.log(error);
    }
  },
  methods: {
    async boughtItem(id) {
      await axios.patch(`http://localhost:3000/items/${id}`, {
        bought: true,
      });
      this.items = this.items.map((item) => {
        if (item.id === id) {
          item.bought = true;
        }
        return item;
      });
    },
    //on double clicking the item, it will call removeItem(id) method
    removeItem(id) {
      axios.delete(`http://localhost:3000/items/${id}`);
      this.items = this.items.filter((item) => item.id !== id);
    },
    //method for adding items in the list
    async addItem() {
      const res = await axios.post(`http://localhost:3000/items`, {
        name: this.itemName,
      });
      this.items = [...this.items, res.data];
      this.itemName = "";
    },
  },
};
</script>

我们来解释一下上面的代码。

<li
    v-for="item of items"
    :class="{ bought: item.bought }"
    :key="item.id"
    @click="boughtItem(item.id)"
    @dblclick="removeItem(item.id)"
>

在这里,我们使用了@click@dblclick 指令来监听DOM事件,并在它们被触发时运行一些JavaScript。当用户点击一个项目时,boughtItem 函数被调用。这将在API中更新所选项目的done 属性为真。当用户双击一个项目时,removeItem 方法被调用,删除该项目。

为了使我们的应用程序不那么赤裸裸,在你的App.vue 文件中添加以下样式。

<style>
#app {
  text-align: center;
  color: #2c3e50;
}
.container {
  background-color: #24e02dd2;
  max-width: 400px;
  margin: 0 auto;
  border-radius: 8px;
}
li {
  font-size: 1.5rem;
  list-style: none;
}
button {
  margin-top: 5px;
  background-color: #3498db;
  border: none;
  color: #ffffff;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
  border-radius: 4px;
}
input {
  margin-top: 5px;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
}
.bought {
  text-decoration: line-through;
}
</style>

在你的浏览器中,你应该看到带有项目列表的应用程序。当你点击这些项目时,它们应该被划掉,当你双击它们时,它们应该被删除。shopping-list

这里是我的GitHub repo,包含完全工作的代码。

总结

在这篇文章中,我们使用json-server 来创建一个你可以使用Axios和Vue 3.0来消费的API。我们使用GETPOSTPATCHDELETE 等HTTP方法与API进行交互。对于更复杂的请求,推荐使用Axios,因为它可以在一个地方对众多请求进行不同的设置。

进一步阅读

编码愉快!


同行评审贡献者:。Geoffrey Mwangi

类似文章

[

How to Create a Reusable React Form component Hero Image

语言

如何创建一个可重复使用的React表单组件

阅读更多

](www.section.io/engineering…

Building a payroll system with next.js Hero Image

语言, Node.js

用Next.js构建一个薪资系统

阅读更多

](www.section.io/engineering…

Creating and Utilizing Decorators in Django example image

架构

在Django中创建和使用装饰器

阅读更多

](www.section.io/engineering…)