vue+mockjs模拟数据分页功能、新增功能、编辑功能、删除功能
Mockjs模拟数据,实现增删改查
1、安装mockjs
npm install mockjs --save-dev
2、mock.js文件
// mock.js 文件 import Mock from mockjs // 引入mockjs const Random = Mock.Random // Mock.Random 是一个工具类,用于生成各种随机数据 const dataList = [] // 用于接受生成数据的数组 for (let i = 0; i < 26; i++) { // 可自定义生成的个数 const template = { id: i, // id Name: Random.name(), // 生成姓名 Address: Random.province() // 生成地址 } dataList.push(template) } // 模拟分页 Mock.mock(http://localhost:8080/api/list, post, (params) => { var listQuery = JSON.parse(params.body) var pageIndex = (listQuery.page - 1) * listQuery.pageSize var [index, size, total] = [pageIndex, listQuery.pageSize, dataList.length] var newDataList = dataList.slice(index * size, (index + 1) * size) return { code: 200, message: success, data: { listQuery: listQuery, tableData: newDataList, tableHead: [{ column: id, columen_comment: 用户id }, { column: Name, columen_comment: 姓名 }, { column: Address, columen_comment: 地址 }], total: total } } }) // 模拟新增数据 Mock.mock(http://localhost:8080/api/add, post, (params) => { var data = JSON.parse(params.body) data.id = dataList.length dataList.push(data) return { code: 200, message: success } }) // 模拟删除数据 Mock.mock(http://localhost:8080/api/delete, post, (params) => { var data = JSON.parse(params.body) dataList.splice(data.id, 1) return { code: 200, message: success } }) // 模拟修改数据 Mock.mock(http://localhost:8080/api/update, post, (params) => { var data = JSON.parse(params.body) /* dataList.map((item) => { if (item.id === data.id) { return data } else { return item } }) */ for (var i in dataList) { if (dataList[i].id === data.id) { // 在数组arr里找到这个id dataList[i] = data } } return { code: 200, message: success, data: data } })
3、在使用到地方引入
//引入 require(@/utils/mock.js) mounted() { this.test() }, methods: { async test() { await axios.post(http://localhost:8080/api/list, { page: 1, pageSize: 30 }).then(res => { console.log(res) }) await axios.post(http://localhost:8080/api/add, { Name: lijn, Address: fhhsdf }).then(res => { console.log(res) }) await axios.post(http://localhost:8080/api/delete, { id: 25 }).then(res => { console.log(res) }) await axios.post(http://localhost:8080/api/update, { id: 26, Name: ljc, Address: 广东省 }).then(res => { console.log(res) }) await axios.post(http://localhost:8080/api/list, { page: 1, pageSize: 30 }).then(res => { console.log(res) }) await axios.post(http://localhost:8080/api/list, { page: 1, pageSize: 30 }).then(res => { console.log(res) }) } }