json-server 快速伪造后台接口

发布于 2022-12-05 12:51:26 字数 3920 浏览 89 评论 0

使用 Vue 也有一段时间了,现在对 Vue 的一些以前没有注意到的点小结一番~

本文均采用 npm 安装依赖

json-server

数据存储的利器啊,我之前是采用 easy-mock,遗憾的是其只能使用 get 请求。在 json-server 中,我们采用 npm install -g json-server 安装依赖。在最外层文件新建 mock 文件,下建 db.json,然后采用 json 格式输入数据。

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

然后改改 script,在 package.json 中,修改 script

"scripts": {
        "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
        "start": "node build/dev-server.js",
        "build": "node build/build.js",
        "mock": "json-server mock/db.json --port 9092",
        "mockdev": "npm run mock & npm run dev"
    },

你可以用 npm run dev 打开项目 npm run mock 打开json-server,npm run mockdev 两个一起打开~~,在 localhost9092 可以看到我们的 mock 数据,端口地址可以在 port 后面改,要对数据进行操作,需设置我们的基地址

let baseUrl = 'http://localhost:9092'; 

配合 axios 使用,即可对数据进行增删改查

import axios from'axios'
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => { type = type.toUpperCase(); url = baseUrl + url; if (type == 'GET') { // searchtry { var res = await axios.get(url) return res } catch (error) { console.error(error) } } elseif(type == 'PUT') { // edittry { await axios.put(url,data.data) } catch (error) { console.error(error) } } elseif(type == 'POST') { // addtry { await axios.post(url,data.data) } catch (error) { console.error(error) } } elseif(type == 'DELETE') { // deletetry { await axios.delete(url,data.data) } catch (error) { console.error(error) } } }

比如我们要对数据中的 posts 进行 get 操作,只需在基地址后加上 /posts,而若是要对其中的 id为1 的进行操作,则在基地址后加上 /posts/1

vuex

使用 vuex 的时候参照了 github 的 vue大项目 elm,觉得这种数据分离的方式特别好,推荐给大家

首先安装依赖 npm install vuex --save

新建文件夹 store,下建 index.js 和 mutation.js,这里我只建了 mutation.js,原版还有 getter.js 和 action.js,但因为项目中没用到,故没有建。

index.js

import Vue from'vue'
import Vuex from'vuex'
import mutations from'./mutations' Vue.use(Vuex) const state = { example: '' } exportdefaultnew Vuex.Store({ state, mutations })

mutation.js

exportdefault {
    setExample (state, newData) {
        state.example = newData
    }
}

从而在我们的工程文件中,引入相应的函数传入相应的数据即可

helloWorld.vue

...mapMutations([
    'setExample'
]),

async initData(){ // 异步大法好
let res = await getData(); this.setExample(res.data) this.data = res.data;
},

service/getData.js

import fetch from'../config/fetch'exportconst getData = () => fetch('/posts', {});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

謌踐踏愛綪

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文