关于vue.js:vue中mockjs的使用

32次阅读

共计 640 个字符,预计需要花费 2 分钟才能阅读完成。

  1. src目录下新建 index.jsresponse目录,response 用于注册各个模块的接口
  2. 编写index.js

    import Mock from 'mockjs'
    
    let moduleList = require.context('./response', true, /.js$/)
    moduleList.keys().forEach(key => {let el = moduleList(key)
      for (const i in el) {if (Object.hasOwnProperty.call(el, i)) el[i]()}
    })
    
    Mock.setup({timeout: '0-100' // 也反对具体数字})
    
    export default Mock

    3. 编写示例 response目录下新建user.js, 内容如下

    import Mock from 'mockjs'
    
    const Random = Mock.Random
    export const getUserList = () => {
     Mock.mock(/user\/getUserList/, 'get', {
        'data|1-10': [
             {
                 'id|+1':0
                 email: '@email',
                 name: '@cname',
                 address: '@county(true)'
             }
        ]
     })
    }

    4. 应用

    // 间接调用接口
    import {getUserList} from '@/api/user'
    
    {
     methods: {getUserList(){getUserList().then(res => console.log(res))
         }
     }
    }

正文完
 0