Bootstrap

掌握Mock.js基本使用:快速模拟API实现增删改查

在项目中使用Mock.js进行增删改查操作,可以模拟后端接口,方便前端开发和测试。下面是一个简单的示例,展示如何在Vue 2项目中使用Mock.js实现增删改查功能。

1. 安装依赖

npm install mockjs --save

2. 配置Mock.js

在项目的根目录下创建一个文件夹mock,并在其中创建一个文件index.js,用于配置Mock.js。

// mock/index.js
import Mock from 'mockjs';

let dataList = [];
const count = 10;
for (let i = 0; i < count; i++) {
  dataList.push(Mock.mock({
    id: '@increment',
    name: '@name',
    age: '@integer(20, 50)',
    address: '@county(true)'
  }));
}

// 获取列表
Mock.mock('/api/data', 'get', () => {
  return {
    code: 200,
    data: dataList
  };
});

// 添加数据
Mock.mock('/api/data', 'post', (options) => {
  const body = JSON.parse(options.body);
  dataList.push(Mock.mock({
    id: '@increment',
    ...body
  }));
  return {
    code: 200,
    message: '添加成功'
  };
});

// 更新数据
Mock.mock(/\/api\/data\/\d+/, 'put', (options) => {
  const body = JSON.parse(options.body);
  const id = parseInt(options.url.split('/').pop());
  dataList = dataList.map(item => item.id === id ? { ...item, ...body } : item);
  return {
    code: 200,
    message: '更新成功'
  };
});

// 删除数据
Mock.mock(/\/api\/data\/\d+/, 'delete', (options) => {
  const id = parseInt(options.url.split('/').pop());
  dataList = dataList.filter(item => item.id !== id);
  return {
    code: 200,
    message: '删除成功'
  };
});

export default Mock;

3. 在Vue项目中引入Mock.js

main.js中引入Mock.js配置文件:

// main.js
import Vue from 'vue';
import App from './App.vue';
import axios from 'axios';
import './mock'; // 引入mock配置

Vue.config.productionTip = false;
Vue.prototype.$axios = axios;

new Vue({
  render: h => h(App),
}).$mount('#app');

4. 创建组件实现增删改查

src/views目录下创建一个组件DataList.vue,实现增删改查功能。

<template>
  <div>
    <h1>Mock.js 增删改查示例</h1>
    <div>
      <input v-model="newData.name" placeholder="Name" />
      <input v-model="newData.age" placeholder="Age" type="number" />
      <input v-model="newData.address" placeholder="Address" />
      <button @click="addData">添加</button>
    </div>
    <ul>
      <li v-for="item in dataList" :key="item.id">
        <div>
          <span>{{ item.name }}</span>
          <span>{{ item.age }}</span>
          <span>{{ item.address }}</span>
          <button @click="editData(item)">编辑</button>
          <button @click="deleteData(item.id)">删除</button>
        </div>
        <div v-if="editingId === item.id">
          <input v-model="editDataObj.name" placeholder="Name" />
          <input v-model="editDataObj.age" placeholder="Age" type="number" />
          <input v-model="editDataObj.address" placeholder="Address" />
          <button @click="updateData(item.id)">更新</button>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataList: [],
      newData: {
        name: '',
        age: '',
        address: ''
      },
      editingId: null,
      editDataObj: {
        name: '',
        age: '',
        address: ''
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.$axios.get('/api/data').then(res => {
        if (res.data.code === 200) {
          this.dataList = res.data.data;
        }
      });
    },
    addData() {
      this.$axios.post('/api/data', this.newData).then(res => {
        if (res.data.code === 200) {
          this.fetchData();
          this.newData = { name: '', age: '', address: '' };
        }
      });
    },
    deleteData(id) {
      this.$axios.delete(`/api/data/${id}`).then(res => {
        if (res.data.code === 200) {
          this.fetchData();
        }
      });
    },
    editData(item) {
      this.editingId = item.id;
      this.editDataObj = { ...item };
    },
    updateData(id) {
      this.$axios.put(`/api/data/${id}`, this.editDataObj).then(res => {
        if (res.data.code === 200) {
          this.fetchData();
          this.editingId = null;
        }
      });
    }
  }
};
</script>

5. 总结

通过上述步骤,我们在Vue 2项目中使用Mock.js成功模拟了一个简单的增删改查操作。

;