1. 程式人生 > 其它 >json-server使用

json-server使用

技術標籤:vue3

作為一個前端開發工程師,在後端還沒有ready的時候,不可避免的要使用mock的資料。很多時候,我們並不想使用簡單的靜
態資料,而是希望自己起一個本地的mock-server來完全模擬請求以及請求回來的過程。json-server是一個很好的可以替
我們完成這一工作的工具。

1、安裝
cnpm i json-server -g
2、新建資料檔案(我建立的是一個api檔案)

在這裡插入圖片描述

3、啟動json-server
json-server api/city.json

在這裡插入圖片描述
因為我json檔案裡面有兩個物件`

{
  "list": [
    {
      "id"
: 1, "title": "bim專案啟動了", "date": "2018-08-12", "likes": 33, "views": 124 }, { "id": 2, "title": "bim專案啟動了", "date": "2018-08-12", "likes"
: 5554, "views": 212 } ], "comments": [ { "id": 1, "news_id": 1, "data": [ { "id": 1, "content": "測試資料" }, { "id": 2, "content"
: "測試資料" } ] }, { "name": "pyl", "id": 2 } ] }

`所以就生成了2個介面。
看見就基本成功了,接下來就是呼叫介面了

methods: {
    json_getdata(params) {
      return axios({
        method: "get",
        url: "http://localhost:3000/list",
        params:{}
      })
    },
    async getdata(){
      const {data} = await this.json_getdata()
      console.log(data);
    }
  },

在這裡插入圖片描述

完成!!
post/patch等等查詢只放程式碼 不放結果了,截圖太費勁了,浪費時間~

post

 json_postdata(data) {
      return axios({
        method: "post",
        url: "http://localhost:3000/list",
        data: {
          title: "bim專案啟動了",
          date: new Date(),
        },
      });
    },
    async postdata() {
      const { data } = await this.json_postdata();
      console.log(data);
    },

patch

json_patchdata(id) {
      return axios({
        method: "patch",
        url: "http://localhost:3000/list/3",
        data: {
          title: "我叫南京黑馬潘奕霖",
        },
      });
    },
    async patchdata() {
      const { data } = await this.json_patchdata();
      console.log(data);
    },

delete懶得寫了 也就那麼回事
附上完整程式碼

<template>
  <div class="home">
    <button @click="getdata">getdata</button>
    <button @click="postdata">post</button>
    <button @click="patchdata">patch</button>
    <button>delete</button>
  </div>
  
</template>

<script>
// @ is an alias to /src

import axios from "axios";
export default {
  name: "Home",
  data() {
    return {
      // num: 123
    };
  },
  methods: {
     json_patchdata(id) {
      return axios({
        method: "patch",
        url: "http://localhost:3000/list/3",
        data: {
          title: "我叫南京黑馬潘10",
        },
      });
    },
    async patchdata() {
      const { data } = await this.json_patchdata();
      console.log(data);
    },
    json_getdata(params) {
      return axios({
        method: "get",
        url: "http://localhost:3000/list",
        params: {},
      });
    },
    async getdata() {
      const { data } = await this.json_getdata();
      console.log(data);
    },
    json_postdata(data) {
      return axios({
        method: "post",
        url: "http://localhost:3000/list",
        data: {
          title: "bim專案啟動了",
          date: new Date(),
        },
      });
    },
    async postdata() {
      const { data } = await this.json_postdata();
      console.log(data);
    },
  },
};
</script>