mockjs的增删改查(vue)

参考文章:vue中使用mockjs实现增删改查

安装开发依赖

npm install mockjs -D

安装mockjs在你的开发依赖上,因为你生产环境用的是正式的接口,安装在开发依赖上可以减少你包的大小。

建立mock文件夹

在src目录中,建立一个mock的文件夹。在mock目录下,建一个index.js和一些其他的js文件(下文是user.js)


mock目录.png

)

这是一个带分页的mock数据,可以实现增删改查的功能。

在hospitals.js中

import Mock from 'mockjs'

const data = Mock.mock({
  'items|30': [{
    id: '@id()',
    name: '@ctitle(2,4)医院',
    description: '@cparagraph',
    status: '@boolean',
    created_at: '@datetime'
  }]
})

export default [
  // 获取列表
  {
    url: '/admin/hospitalList',
    type: 'get',
    response: config => {
      const items = data.items
      const { name, currentPage = 1, pageSize = 20 } = config.query
        const mockList = items.filter(user => {
          if (name && user.name.indexOf(name) === -1) return false
          return true
        })
        const pageList = mockList.filter((item, index) => index < pageSize * currentPage && index >= pageSize * (currentPage - 1))

      return {
        code: 20000,
        data: {
          total: mockList.length,
          items: pageList
        }
      }
    }
  },
  // 创建or编辑
  {
    url: '/admin/createHospital',
    type: 'post',
    response: config => {
      let obj  = config.query
      if (obj.id) {
        data.items.some(u => {
          if (u.id === obj.id) {
            u.name = obj.name
            u.description = obj.description
            u.status = obj.status
            return true
          }
        })
        return {
          code: 20000,
          message: '修改成功'
        }
      }else{
        obj.id = Mock.Random.id()
        obj.created_at = Mock.mock('@now')
        data.items.unshift(obj)

        return {
          code: 20000,
          message: '添加成功'
        }
      }

    }
  },
  // 删除
  {
    url: '/admin/delHospital',
    type: 'get',
    response: config => {
      let obj  = config.query
      if (!obj.id) {
        return {
          code: -999,
          message: '参数不正确'
        }
      } else {
        data.items = data.items.filter(u => u.id !== obj.id)
        return {
          code: 20000,
          message: '删除成功'
        }
      }
    }
  },
  // 批量删除
  {
    url: '/admin/batchremove/hospital',
    type: 'post',
    response: config => {
      let str  = config.query.idStr
      let arr = str.split(',')
      data.items = data.items.filter(u => !arr.includes(u.id))
      return {
        code: 20000,
          message: '批量删除成功'
      }
    }
  }

]

在index.js中

import Mock from 'mockjs'
import { param2Obj } from '../src/utils'

import user from './user'
import hospitals from './hospitals'

const mocks = [
  ...user,
  ...hospitals
]

// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
export function mockXHR() {
  // mock patch
  // https://github.com/nuysoft/Mock/issues/300
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function() {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function(options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        // https://expressjs.com/en/4x/api.html#req
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

// for mock server
const responseFake = (url, type, respond) => {
  return {
    url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
    type: type || 'get',
    response(req, res) {
      console.log('request invoke:' + req.path)
      res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
    }
  }
}

export default mocks.map(route => {
  return responseFake(route.url, route.type, route.response)
})

在main.js中

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

在组件中按自己平时调用接口使用的习惯即可

遇到的问题

mockjs从数组中随机选择n项组成新数组?

const data = Mock.mock({
  'items|30': [{
    'id|+1': 1,
    account: '@last()',
    nickname: '@cname()',
    role: ['Administrator'],
    permissions: function () {
      let arr = ['All permission','Dashboard','Login','User setting','Auth management'];
      let count = Math.floor(Math.random() * arr.length + 1);
      let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
      while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
      }
      return shuffled.slice(min);
    },
    created_at: '@datetime',
    updated_at: '@datetime',
  }]
})

生成随机函数的方法:

// 方法一: 打乱数组的顺序,然后slice 切割出来新的数组
function a() {
      let arr = ['All permission','Dashboard','Login','User setting','Auth management'];
      let count = Math.floor(Math.random() * arr.length + 1);
      let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
      while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
      }
      return shuffled.slice(min);
    }
// 方法二:
function a() {
      let arr = ['All permission','Dashboard','Login','User setting','Auth management'];
      let count = Math.floor(Math.random() * arr.length + 1);
      var  i = arr.length, min = i - count ;
    arr.sort((a,b)=>{
        return Math.random() > 0.5 ? a-b : b-a
    })
    return arr.slice(min);
    }
// 方法三:
function a() {
      let arr = ['All permission','Dashboard','Login','User setting','Auth management'];
      let count = Math.floor(Math.random() * arr.length + 1);
      let newArr = [];
      var pick = function () {
           var index = Math.ceil((arr.length * Math.random())) - 1;
           return arr.splice(index, 1);
       }
       for (var i = 0; i < count ; i++) {
           newArr.push(pick()[0]);
      }
      return newArr;
    }

你可能感兴趣的:(mockjs的增删改查(vue))