zoukankan      html  css  js  c++  java
  • Vue项目中使用Mockjs造假数据


    需求场景:要get请求接口'/api/userInfo/list'
     
    项目准备:
    首先,安装项目中mockjs包、axios
    npm install mockjs axios
    然后,src根目录下新建mock文件夹和mock.js、urls.js
    (目录结构不强求,主要还是看你项目的划分。也可以单独出一个request文件,放axios.js、mock.js、和专门整理接口用的url.js)


    user.vue文件中,接口请求代码(以axios为例):
    <template>
      <div class="api-element">
        <div class="area">
          <el-table :data="userTableData" >
            <el-table-column fixed label="日期" prop="date" width="150"></el-table-column>
            <el-table-column label="姓名" prop="name" width="120"></el-table-column>
            <el-table-column label="省份" prop="province" width="120"></el-table-column>
            <el-table-column label="市区" prop="city" width="120"></el-table-column>
            <el-table-column label="地址" prop="address" width="300"></el-table-column>
            <el-table-column label="邮编" prop="zip" width="120"></el-table-column>
          </el-table>
        </div>
      </div>
    </template>
    <script>
    import axios from 'axios' // 引入axios
    import urls from '@/mock/urls'  // 引入实现准备好的接口请求相关配置
    export default {
      name: 'MockTest',
      data() {
        return {
          userTableData: [] // 定义需要的数据
        }
      },
      mounted() {
        // 数据mock、请求拦截
        axios[urls.userTableData.type](urls.userTableData.url)
          .then((response) => {
            this.userTableData = response && response.data
            log(this.userTableData);
          })
          .catch(function (error) {
            log(error);
          });
      },
    }
    </script>
    接口相关配置文件urls.js:
    主要记录每条接口需要请求的地址(加过代理的)、请求的方式(get等,方便管理)
    export default {
        userTableData: {
            url: '/api/userInfo/list',
            type: 'get'
        }
    }
    mock.js文件内部:
    首先,引入mockjs和需要的变量值urls.js
    import Mock, { Random } from 'mockjs'
    import urls from './urls'
    然后,定义第一个假数据userTableData,是一个长度为10的数组,数组每一项都是对象,对象键根据vue中表格需要进行配置。
    let params = Mock.mock({ // 数据池
        'userTableData|10': [{ // 图表过滤所需数据
            'name': '@cname',
            'date': '@date',
            'province': '@province',
            'city': '@city',
            'address': '@county(true) @ctitle() @natural(1000,9999) 号',
            'zip': '@zip'
        }]
    })
    // 设置请求时长200-600毫秒,模拟真实接口请求场景
    Mock.setup({
        timeout: '200-600'
    })
    // 拦截urls.userTableData.url对应地址的请求,方式urls.userTableData.type,返回值为params.userTableData
    Mock.mock(urls.userTableData.url, urls.userTableData.type, params.userTableData) // 请求该接口时,拦截请求并返回对应数据
    
    最后,观察vue文件中的ajax请求,返回的response.data的数据就是我们mock的params.userTableData假数据。大功告成,可以专心写逻辑了。
     
     
     
     
  • 相关阅读:
    ES6介绍
    django-缓存
    Python标准模块--functools
    python-深浅拷贝
    Django专题-ugettext_lazy
    PHP 连接 MySQL
    PHP 过滤器
    PHP session
    PHP cookie
    PHP 文件上传
  • 原文地址:https://www.cnblogs.com/padding1015/p/12682796.html
Copyright © 2011-2022 走看看