mockjs analog implementation CRUD

/*mUtils.js*/
export const param2Obj = url => {
    const search = url.split('?')[1]
    if (!search) {
      return {}
    }
    return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
  }

  

/*money.js*/
import Mock from 'mockjs'
import * as mUtils from '@/utils/mUtils'
let List = []
const count = 60
let typelist = [1, 2, 3, 4, 5, 6, 7, 8]
for (let i = 0; i < count; i++) {
  List.push(Mock.mock({
    id: Mock.Random.guid(),
    username: Mock.Random.cname(),
    address: Mock.mock('@county(true)'),
    createTime: Mock.Random.datetime(),
    income: Mock.Random.float(0, 9999, 2,2),
    pay: Mock.Random.float(-5999, 0, 2,2),
    accoutCash: Mock.Random.float(0, 9999, 2,2),
    'incomePayType|1': typelist
  }))
}
export default {
  /* 获取列表getMoneyList*/
  getMoneyList: config => {
    const { name, page = 1, limit = 20 } = mUtils.param2Obj(config.url)
	console.log(mUtils.param2Obj(config.url))
	console.log(page+"++"+limit)
    const mockList = List.filter(user => {
      if (name && user.username.indexOf(name) === -1) return false
      return true
    })
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    return {
      code: 200,
      data: {
        total: mockList.length,
        moneyList: pageList
      }
    }
  },
  /** 增加资金信息createMoney*/
  createMoney: config => {
    const { username, address, income, pay , accoutCash, incomePayType } = mUtils.param2Obj(config.url)
    List.push({
      id: Mock.Random.guid(),
      username: username,
      address: address,
      createTime: Mock.Random.now(),
      income: income,
      pay: pay,
      accoutCash: accoutCash,
      incomePayType: incomePayType
    })
    return {
      code: 200,
      data: {
        message: '添加成功'
      }
    }
  },
  /*** 删除用户deleteMoney */
  deleteMoney: config => {
    const { id } = mUtils.param2Obj(config.url)
    if (!id) {
      return {
        code: -999, 
        Message: 'parameter is incorrect' 
      } 
    } the else { 
      List List.filter = (U => u.id ID ==!) 
      return { 
        code: 200 is, 
        Data: { 
          Message: 'successfully deleted' 
        } 
      } 
    } 
  } 
  / * delete batch * / batchremoveMoney : config => { 
    the console.log (config); 
    // the console.log (mUtils.param2Obj (config.url)); 
    the let {} = mUtils.param2Obj IDS (config.url ) 
    the console.log (IDS); 
    IDS = ids.split ( ',') 
    List List.filter = (U => ids.includes (u.id!)) 
    return { 
      Data: { 
        Message: 'bulk successfully deleted'

  
      code: 200,
      }
    }
  },
  /*修改用户 */
  updateMoney: config => {
    const { id,username, address, income, pay , accoutCash, incomePayType } = mUtils.param2Obj(config.url)
    List.some(u => {
      if (u.id === id) {
        u.username = username
        u.address = address
        u.income = income
        u.pay = pay
        u.accoutCash = accoutCash
        u.incomePayType = incomePayType
        return true
      }
    })
    return {
      code: 200,
      data: {
        message: '编辑成功'
      }
    }
  }
}

  

/*index.js*/
Mock from Import 'mockjs' 
Import tableAPI from './money' 
Import salesAPI from './sales' 
Import userAPI from './user' 
// set global delay no delay if sometimes not detect changes proposed to retain data 
Mock.setup ({ 
    timeout: '300-600' 
}) 
// funds associated 
Mock.mock (/ \ / money \ / GET /, 'GET', tableAPI.getMoneyList) 
Mock.mock (/ \ / money \ / Remove /, 'GET', tableAPI.deleteMoney) 
Mock.mock (/ \ / Money \ / batchremove /, 'GET', tableAPI.batchremoveMoney) 
Mock.mock (/ \ / Money \ / the Add /, 'GET', tableAPI. createMoney) 
Mock.mock (/ \ / Money \ / Edit /, 'GET', tableAPI.updateMoney) 
// Sales related 
Mock.mock (/ \ / sales \ / get /, 'get', salesAPI.getSalesList)
// user相关
Mock.mock(/\/user\/login/, 'get', userAPI.login)
Mock.mock(/\/user\/logout/, 'get', userAPI.logout)
Mock.mock(/\/user\/info\/get/, 'get', userAPI.getUserInfo)
Mock.mock(/\/user\/list\/get/, 'get', userAPI.getUserList)

  

/*Api.js接口管理*/
import request from '@/utils/axios' export function getMoneyIncomePay(params) { return request({ url: '/money/get', method: 'get', params: params }) } export function addMoney(params) { return request({ url: '/money/add', method: 'get', params: params }) } export function removeMoney(params) { return request({ url: '/money/remove', method: 'get', params: params }) } export function batchremoveMoney(params) { return request({ url: '/money/batchremove', method: 'get', params: params }) } export function updateMoney(params) { return request({ url: '/money/edit', method: 'get', params: params }) }

  

/*在组件里使用*/
<template> <div class="fillcontain"> <search-item @showDialog="showAddFundDialog" @searchList="getMoneyList" @onBatchDelMoney="onBatchDelMoney"></search-item> <div class="table_container"> <el-table v-loading="loading" :data="tableData" style="width: 100%" align='center' @select="selectTable" @select-all="selectAll" > <el-table-column v-if="idFlag" prop="id" label="id" align='center' width="180"> </el-table-column> <el-table-column type="selection" align='center' width="40"> </el-table-column> <el-table-column prop="username" label="用户姓名" align='center' width="80"> </el-table-column> <el-table-column prop="address" label="籍贯" align='center' > </el-table-column> <el-table-column prop="createTime" label="投资时间" align='center' sortable width="170"> <template slot-scope="scope"> <el-icon name="time"></el-icon> <span style="margin-left: 10px">{{ scope.row.createTime }}</span> </template> </el-table-column> <el-table-column prop="incomePayType" label="收支类型" align='center' width="130" :formatter="formatterType" :filters="fields.incomePayType.filter.list" :filter-method="filterType"> </el-table-column> <el-table-column prop="income" label="收入" align='center' width="130" sortable> <template slot-scope="scope"> <span style="color:#00d053">+ {{ scope.row.income }}</span> </template> </el-table-column> <el-table-column prop="pay" align = left = 'Center' label = "spending" width="130" sortable> <template slot-scope="scope"> <span style="color:#f56767">{{ getPay(scope.row.pay) }}</span> </template> </el-table-column> <el-table-column prop="accoutCash" label="账户现金" align='center' width="130" sortable> <template slot-scope="scope"> <span style="color:#4db3ff">{{ scope.row.accoutCash }}</span> </template> </el-table-column> <el-table-column prop="operation" align='center' label="操作" width="180"> <template slot-scope='scope'> <el-button type="warning" icon='edit' size="mini" @click='onEditMoney(scope.row)' >编辑</el-button> <el-button type="danger" icon='delete' size="mini" @click='onDeleteMoney(scope.row,scope.$index)' >删除</el-button> </template> </el-table-column> </el-table> <pagination :pageTotal="pageTotal" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"></pagination> <addFundDialog v-if="addFundDialog.show" :isShow="addFundDialog.show" :dialogRow="addFundDialog.dialogRow" @getFundList="getMoneyList" @closeDialog="hideAddFundDialog"></addFundDialog> </div> </div> </template> <script> import { mapGetters } from "vuex"; import * as mutils from '@/utils/mUtils' import SearchItem from "./components/searchItem"; import AddFundDialog from "./components/addFundDialog"; import Pagination from "@/components/pagination"; import { getMoneyIncomePay , removeMoney, batchremoveMoney } from "@/api/money"; import axios from "axios" export default { data(){ return { tableData: [], tableHeight:0, loading:true, idFlag:false, isShow:false, // 是否显示资金modal,默认为falselimit editid:'', rowIds:[], sortnum:0, format_type_list: { 0: 'Withdrawal', 1: 'withdrawals fees', 2: 'Withdrawal lock ", 3:' financial services exit ', 4:' Buy appropriate and surplus ', 5:' recharge ', 6:' coupons', 7: 'recharge coupon', 8: 'transfer' }, addFundDialog: { Show: to false, dialogRow: {} }, incomePayData: { Page:. 1, limit: 20 is, name: '' }, pageTotal: 0, // list for screening Fields: { incomePayType: { filter: { List: [{ text: 'withdrawal', value: 0 }, { text: 'withdrawals fees', value:. 1 }, { text : 'withdrawal locking', value: 2 }, { text: 'exit financial services', value:3 }, { Text: 'Buy appropriate and surplus' value:. 4 }, { text: 'recharge', value:. 5 }, { text: 'Coupons' value:. 6 }, { text: 'recharge coupon' value:. 7 }, { text: 'transfer', value:. 8 }], multiple: true } }, }, } }, components:{ SearchItem, AddFundDialog, Pagination }, computed:{ ...mapGetters(['search']) }, mounted() { this.getMoneyList(); // this.setTableHeight(); // window.onresize = () => { // this.setTableHeight(); // } }, methods: { setTableHeight(){ this.$nextTick(() => { this.tableHeight = document.body.clientHeight - 300 }) }, // 获取资金列表数据 getMoneyList(){ const para = Object.assign({},this.incomePayData,this.search); getMoneyIncomePay(para).then(res => { console.log(res) this.loading = false; this.pageTotal = res.data.total // console.log(res) this.tableData = res.data.moneyList }) }, // 显示资金弹框 showAddFundDialog(val){ . store.commit the this $ ( 'SET_DIALOG_TITLE', Val) this.addFundDialog.show = to true; }, hideAddFundDialog () { this.addFundDialog.show = to false; }, // vertical tab handleCurrentChange (Val) { this.incomePayData. = Val Page; this.getMoneyList () }, // how many per page handleSizeChange (Val) { this.incomePayData.limit = Val; this.getMoneyList () }, getPay (Val) { IF (mutils.isInteger (Val )) { return -val; }else{ return val; } }, /** * 格式化状态 */ formatterType(item) { const type = parseInt(item.incomePayType); return this.format_type_list[type]; }, filterType(value, item) { const type = parseInt(item.incomePayType); return this.format_type_list[value] == this.format_type_list[type]; }, // 编辑操作方法 onEditMoney(row){ = Row this.addFundDialog.dialogRow; this.showAddFundDialog (); }, // delete data onDeleteMoney (Row) { the this $ Confirm The ( 'confirmation to delete the record?', 'tips', {. of the type: 'warning' } ) .then (() => { const = {para ID: row.id} removeMoney (para) .then (RES => { . the this Message $ ({ Message: 'successfully deleted', type: 'success' }) this.getMoneyList () }) }) .Catch (() => {}) }, onBatchDelMoney () { . The this $ Confirm The ( 'confirm delete batch records?', 'Tips', { of the type: 'warning' }) .then (() = > { const IDS = this.rowIds.map (Item => item.id) .toString () const = {para IDS: IDS} batchremoveMoney (para) .then (RES => { . the this Message $ ({ Message: ' batch deleted successfully ', of the type:' success' }) the this.getMoneyList() }) }) .Catch (() => {}) }, // Checkbox events triggered when the user manually check data line selectTable (Val, Row) { this.setSearchBtn (Val); }, // user select all when the event is triggered checkbox a selectAll (Val) { val.forEach ((Item) => { this.rowIds.push (item.id); }); this.setSearchBtn (Val); }, setSearchBtn (Val) { the let isFlag to true =; IF (val.length> 0) { isFlag = to false; } the else { isFlag = true; } this.$store.commit('SET_SEARCHBTN_DISABLED',isFlag); } }, } </script> <style lang="less" scoped> .table_container{ padding: 10px; background: #fff; border-radius: 2px; } .el-dialog--small{ width: 600px !important; } .pagination{ text-align: left; margin-top: 10px; } </style>

  

Guess you like

Origin www.cnblogs.com/kaijiangyugty/p/11612989.html