json-server与axios的简单使用

本文介绍了json-server的安装、创建JSON数据、启动服务及RESTful接口规则。接着详细讲解了axios如何查询所有数据、删除单条、实时查询、新增数据,并在Vue项目中封装axios为公共函数的方法,提升代码复用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、json-server的简单使用

json-server参考链接

1、安装

npm install -g json-server

2、新建json数据

  • 新建一个文件夹
  • 在此文件夹中新建db.json文件,数据如下所示
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ]
}

3、启动服务

在此文件位置下输入如下命令:

json-server --watch db.json


可点击该链接查看是否能正常使用。
在这里插入图片描述

4、接口规则-RESTful说明

接口地址请求方式及适用情况
/postsGET查询所有数据
/posts/idGET查询单条数据
/postsPOST添加,提交的参数在请求体 {title,author};id为数字,每次添加会自动加1
/posts/idDELETE删除
/posts/idPUT修改 请求体{title,author} 全部修改
/posts/idPATCH修改 请求体{title} 个别修改

二、axios部分使用

axios参考链接

1、查询所有数据

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="../libs/bootstrap/css/bootstrap.min.css" />
    <script src="../libs/vue.js"></script>
    <script src="../libs/axios.min.js"></script>
  </head>
  <body>
    <div id="app" class="container">
      <div class="form-group">
	        <label class="sr-only" for="keywords"></label>
	        <input
	          type="text"
	          class="form-control"
	          id="keywords"
	          placeholder="搜索标题"
	          v-model="searchWords"
	          v-focus
	        />
      </div>
      <table class="table table-bordered">
        <tr>
          <th>编号</th>
          <th>标题</th>
          <th>作者</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index)  in bookList" :key="item.id">
          <td>{{index+1}}</td>
          <td>{{item.title}}</td>
          <td>{{item.author}}</td>
          <td>
            <button type="button" class="btn btn-danger" @click="del(item.id)">
              删除
            </button>
          </td>
        </tr>
      </table>
    </div>
    <script>
      const vm = new Vue({
        el: "#app",
        data: {
          bookList: [],
          searchWords: '',
        },
        created() {
          this.getAllList();
        },
        methods: {
          //查询所有数据
          getAllList() {
            axios
              .get("http://localhost:3000/posts")
              .then((res) => {
                this.bookList = res.data;
              })
              .catch((err) => {
                console.log(err);
              });
          },
        },
      });
    </script>
  </body>
</html>

2、删除单条数据

//删除数据
          del(id) {
            if (confirm("确认删除该条数据吗?")) {
              axios
                .delete(`http://localhost:3000/posts/${id}`)
                .then((res) => {
                  this.getAllList();
                })
                .catch((err) => {
                  console.log("###del##" + err);
                });
            }
          },

3、实时查询

 //实时查询
        watch: {
          //监听searchWords是否改变
          searchWords() {
            axios
              .get("http://localhost:3000/posts", {
                params: {
                  title_like: this.searchWords,
                },
              })
              .then((res) => {
                // 接收模糊查询的列表
                this.bookList = res.data;
              })
              .catch((err) => {
                console.log("###searchWords##" + err);
              });
          },
        },

4、实现数据新增

//实现数据新增
          addBook() {
            if (this.title.trim() && this.author.trim()) {
              axios
                .post(`http://localhost:3000/posts`, {
                  title: this.title,
                  author: this.author,
                })
                .then((res) => {
                  this.getAllList();
                  //情况输入框
                  this.title = "";
                  this.author = "";
                })
                .catch((err) => {
                  console.log("###addBook##" + err);
                });
            } else {
              alert("请输入有效数据进行新增!");
              return;
            }
          },

5、在Vue项目中,如何将Axios封装成公共函数

  • 方法:将axios定义到Vue原型上

未将axios定义到Vue原型上时,每个组件需要用到axios时,都需要import

<script>
import Axios from "axios";
export default {
  data() {
    return {
      list: [],
    };
  },
  methods: {
    getList() {
      Axios.get("http://localhost:6005/heroList").then((res) => {
        this.list = res.data;
      });
    },
    addHero() {
      this.$router.push("/addHero");
    },
  },
  mounted() {
    this.getList();
  },
};
</script>

将axios定义到Vue原型上后

  • 步骤1:在路由定义文件中,此处是index.js,将axios定义到Vue原型上
//将axios变成公共方法
import Axios from "axios";
Vue.prototype.$request = Axios;
  • 步骤2:组件中使用axios发起请求时,使用this.$request,无需import axios
<script>
// import Axios from "axios";
export default {
  data() {
    return {
      list: [],
    };
  },
  methods: {
    getList() {
      this.$request.get("http://localhost:6005/heroList").then((res) => {
        this.list = res.data;
      });
    },
    addHero() {
      this.$router.push("/addHero");
    },
  },
  mounted() {
    this.getList();
  },
};
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值