Vue中使用mockjs

关于vue中mockjs的使用:

参考:https://www.cnblogs.com/tzm-001/p/10382534.html

Mockjs官网文档:http://mockjs.com/

具体做法:

1、首先在api文件夹下

 以user.js为例

user.js:定义请求方法和url

import request from '@/utils/axios'


export function login(params) {
  return request({
    url: '/user/login',
    method: 'get',
    data:params
  })
}
export function logout(params) {
  return request({
    url: '/user/logout',
    method: 'get',
    data:params
  })
}


export function getUserInfo(params) {
  return request({
    url: '/user/info/get',
    method: 'get',
    data:params
  })
}

export function getUserList(reqData) {
  return request({
    url:'/user/list/get',
    method: 'get',
    data: reqData
  })
}
View Code

axios.js:

import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import store from '../store';
import { getToken } from '@/utils/auth';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers = {
        Authorization: 'Token' + getToken('Token') // 携带权限参数
      };
    }
    return config;
  },
  err => {
    Promise.reject(err);
  }
);

// response拦截器
service.interceptors.response.use(
  response => {
    /**
     * code:200,接口正常返回;
     */
    const res = response.data;
    if (res.code !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      });
      // 根据服务端约定的状态码:5001:非法的token; 5002:其他客户端登录了; 5004:Token 过期了;
      if (res.code === 5001 || res.code === 5002 || res.code === 5004) {
        MessageBox.confirm(
          '你已被登出,可以取消继续留在该页面,或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload(); // 为了重新实例化vue-router对象 避免bug
          });
        });
      }
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('error');
    } else {
      // res.code === 200,正常返回数据
      return response.data;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
View Code

2、mock文件:

 安装:

npm install mockjs

仍以user.js为例:

使用mock定义好数据和方法:

import Mock from 'mockjs';
import * as mUtils from '@/utils/mUtils';

const List = [];
const count = 1000;
const typelist = ['联通', '移动', '电信', '铁通'];

for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Mock.Random.guid(),
      sortnum: i + 1,
      username: Mock.Random.cname(),
      address: Mock.Random.city(),
      createTime: Mock.Random.datetime(),
      updateTime: Mock.Random.now(),
      ip: Mock.mock('@ip'),
      region: Mock.Random.region(),
      areaId: /\d{7}/,
      email: Mock.Random.email(),
      'isp|1': typelist
    })
  );
}

export default {
  // 用户登录
  login: config => {
    const data = JSON.parse(config.body);
    let userList = {};
    if (data.username === 'admin') {
      userList = {
        token: 'admin',
        name: '管理员'
      };
    } else if (data.username === 'editor') {
      userList = {
        token: 'editor',
        name: '赵晓编'
      };
    } else {
      return {
        code: -1,
        data: {
          msg: '用户名错误',
          status: 'fail'
        }
      };
    }
    return {
      code: 200,
      data: {
        userList: userList
      }
    };
  },
  // 用户登出
  logout: config => {
    return {
      code: 200,
      data: {
        userList: ''
      }
    };
  },
  // 获取登录用户信息
  getUserInfo: config => {
    const data = JSON.parse(config.body);
    let userList = {};
    if (data.token === 'admin') {
      userList = {
        roles: ['admin'],
        name: 'admin',
        avatar:
          'https://wx.qlogo.cn/mmopen/vi_32/un2HbJJc6eiaviaibvMgiasFNlVDlNOb9E6WCpCrsO4wMMhHIbsvTkAbIehLwROVFlu8dLMcg00t3ZtOcgCCdcxlZA/132'
      };
    } else if (data.token === 'editor') {
      userList = {
        roles: ['editor'],
        name: 'editor',
        avatar:
          'https://mirror-gold-cdn.xitu.io/168e088859e325b9d85?imageView2/1/w/100/h/100/q/85/format/webp/interlace/1'
      };
    } else {
      userList = {};
    }
    return {
      code: 200,
      data: {
        userList: userList
      }
    };
  },
  /**
   * 获取用户列表
   * 要带参数 name, page, limt; name可以不填, page,limit有默认值。
   * @param name, page, limit
   * @return {{code: number, count: number, data: *[]}}
   */
  getUserList: config => {
    const { limit, page } = JSON.parse(config.body);
    const mockList = List;
    const userList = mockList.filter(
      (item, index) => index < limit * page && index >= limit * (page - 1)
    );
    return {
      code: 200,
      data: {
        total: mockList.length,
        userList: userList
      }
    };
  }
};
View Code

在mock文件夹下的index.js中:

import Mock from 'mockjs';

// process.env.NODE_ENV === 'development' ? Vue.use(Mock) : null;

import userAPI from './user';
import salesAPI from './sales';

// 设置全局延时, 没有延时的话会检测不到数据的变化
Mock.setup({
  timeout: '300-600'
});

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);
Mock.mock(/\/sales\/get/, 'get', salesAPI.getSalesList);

export default Mock;
View Code

3、在src的main.js中:

import '@/mock/index.js';

 

posted @ 2020-07-12 18:50  haha-uu  阅读(1531)  评论(0编辑  收藏  举报