前后端分离开发已成大势所趋, 基本上大部分公司的开发模式都是如此, 那如何自己本地实现一个数据 mock 呢? 当然你也可以使用在线的工具, 比如 easymock https://www.easy-mock.com/login 也可以实现 mock 数据, 但是如果追求稳定性, 还是本地搭一套环境吧. 下面我介绍的是使用了 vue-cli 本身自带的功能实现 mock 数据.
初始化项目
(1) 使用 vue-cli 初始化
vue create mock-demo
全部采用默认即可
(2) 创建配置文件
在项目根目录下创建 vue.config.JS 配置文件. 内容如下:
- const bodyParser = require("body-parser");
- const isProduction = process.env.NODE_ENV === "production";
- let feMock;
- if (!isProduction) {
- feMock = require("./mockApi");
- }
- module.exports = {
- publicPath: isProduction ? "././" : "",
- pages: {
- index: {
- entry: "src/main.js",
- template: "public/index.html",
- filename: "index.html"
- }
- },
- devServer: {
- before: App => {
- // 关键代码
- App.use(bodyParser.JSON());
- App.use(bodyParser.urlencoded({ extended: true }));
- if (!isProduction) {
- feMock(App);
- }
- }
- }
- };
这里主要是利用了 webpack-dev-server 实现的 mock 功能, 为了实现接口请求, 当然需要提前安装 axios,body-parser.
NPM i axios body-parser -S
编写 mock 的 API
(1) 在项目根目录新建文件夹 mockApi, 新建 index.JS
- const feMock = App => {
- App.get("/mock/api/news", function(req, res) {
- res.JSON({
- name: "tom"
- });
- });
- };
- module.exports=feMock;
(2) 在 src 目录下新建一个 API 文件夹, 新建文件 index.JS
- const prefix = "/mock";
- export default {
- methods: {
- _testMock() {
- return this.$http.get(`${prefix}/api/news`);
- }
- }
- };
这里的请求路径一定要和上一步 mock 数据的路径保持一致. 等后端写好接口之后, 统一修改此文件里的 prefix 接口即可.
组件使用
(1) 在 App.vue 里使用
- <script>
- import API from "./api";
- export default {
- name: "App",
- mixins: [API],
- mounted() {
- this.testMock();
- this.testMock1();
- this.testPostMock();
- },
- methods: {
- testMock() {
- this._testMock()
- .then(res => {
- console.log(res);
- })
- .catch(err => {
- console.log(err);
- });
- }
- }
- };
- </script>
正常启动项目后, 在浏览器 network 里就可以看到请求了, 初始功能实现.
优化
(1) 如果项目中多个人写多个 mock 文件怎么整呢?
(2) 能不能直接扫描特定目录加载 mock 文件呢? 是否可以有一个统一的对外入口, 每个人只需要写自己的 mock 文件, 不用修改出口?
解决办法
(1) 在 mockApi 文件夹下新建一个 mockList 文件夹, 之后所有人的 mock 接口写在这里. 示例如下:
在 mockList 中新建一个 test.JS
- function testMock(App) {
- App.get("/mock/api/news", function(req, res) {
- res.JSON({
- name: "tom"
- });
- });
- }
- function testPostMock(App) {
- App.post("/mock/api/news", function(req, res) {
- console.log(req.body);
- setTimeout(function() {
- res.JSON({
- code: 0,
- data: "success",
- desc: ""
- });
- }, 500);
- });
- }
- module.exports = [testMock, testPostMock];
在 mockList 中新建一个 test1.JS
- function testMock1(App) {
- App.get("/mock/api/news1", function(req, res) {
- res.JSON({
- name: "jack"
- });
- });
- }
- module.exports = [testMock1];
(2) 修改 mockApi/index.JS 文件
- const fs = require("fs");
- const path = __dirname;
- const files = fs.readdirSync(path + "/mockList");
- const mockList = [];
- files.forEach(function(filename) {
- let model = require(path + "/mockList/" + filename);
- mockList.push(...model);
- });
- function handleMock(App) {
- mockList.forEach(func => {
- func(App);
- });
- }
- module.exports = handleMock;
引入 fs, 自动读取设定目录下的文件, 这样配置好之后, 其他人只管写自己的 mock 接口, 不需要去修改这个对外的文件, 这样就完美解决了.
示例代码目录结构如下:
来源: http://www.tuicool.com/articles/NvMfmuq