vue进阶3 - Mock.js(生成随机数据,模拟Ajax请求)

一、安装

1.安装mock、axios

npm install mockjs axios

2、安装axios-mock-adapter

axios-mock-adapter是axios与mock配置器,是axios的模拟调试器

npm install axios-mock-adapter --save-dev

二、创建mock文件

1.新建src/mock/data/user.js,生成随机数据

import Mock from 'mockjs'; // 导入mockjs 模块

let Users = []; // 定义我们需要的数据
for (let i = 0; i <= 90; i++) {
      Users.push(Mock.mock({ // 根据数据模板生成模拟数据
        id: Mock.Random.guid(), // 随机生成一个id
        name: Mock.Random.cname(), // 随机生成一个常见的中文姓名。
        addr: Mock.mock('@county(true)'), // @county(true)为数据模板
        'age|18-60': 1, // 'age|18-60': 1 为数据模板
        birth: Mock.Random.date(), // 随机生成日期
        sex: Mock.Random.integer(0, 1), // 随机生成整数, min:0, max1,
    }));
}
const LoginUsers = [ // 制造登录账号,便于模拟登陆测试
    {
        id: 1,
        username: 'admin1',
        password: '123456',
        name: '王某某'
    },
    {
        id: 2,
        username: 'admin2',
        password: '123456',
        name: '陈某某'
    }
]
export { // 导出列表数据
  LoginUsers,Users
};

2.新建src/mock.mock.js,模拟ajax请求的接口,生成并返回模拟数据

reply的参数为 (status, data, headers)

configt指前台传过来的数据

resolve([状态值,{返回的数据}])

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { LoginUsers, Users } from './data/user'
let _Users = Users;
export default {
    start() { //初始化函数
        let mock = new MockAdapter(axios); // 创建 MockAdapter 实例
        //登录
        mock.onPost('/login').reply(config => {
            let {username, password} = JSON.parse(config.data);
            return new Promise((resolve, reject) => {
                let user = null;
                setTimeout(() => {
                    let hasUser = LoginUsers.some(u => {
                        if(u.username === username && u.password === password) {
                            user= JSON.parse(JSON.stringify(u));
                            user.password = undefined;
                            return true;
                        }
                    });
                    if(hasUser) {
                        resolve([200, { code:200, msg: '登录成功', user }]);
                    } else {
                        resolve([200, { code: 500, msg: '账号或者密码错误' }]);
                    }
                },1000);
            });
        });
    
        // 获取用户列表
        mock.onGet('/user/list').reply(confige => {
            let {name} = confige.params;
            let mockUsers = _Users.filter(user => {
                if(name && user.name.indexOf(name) == -1) return false;
                return true;
            });
            return new Promise((resolve, reject) => {
                setTimeout(()=> {
                    resolve([200, {
                        users: mockUsers
                    }])
                }, 1000);
            });
        });
    }
}

3.新建src/mock/index.js,导入同级下mock.js的内容,并且导出

import mock from './mock'; 
export default mock; 

4.打开src/main.js, 引入mock,全局加载mock并执行初始化函数

import Mock from './mock'
Mock.start();

三、封装api函数

1.新建src/api/api.js,把所有接口都写到一个文件里面,封装成一个个函数,便于修改与管理

    import axios from 'axios';
    
    export const Login = params => { return axios.post(`/login`, params).then(res.data); };
    export const getUserList = params => { return axios.get(`/user/list`, { params: params }); }

2.新建src/api/index.js

import * as api from './api';

export default api; 

四、调用接口

新建src/pages/login.vue
<template>
    <div class="login">
        <el-form :model="form2" :rules="rules2" ref="form2" label-width="0" class="login2">
            <h1>登录</h1>
            <el-form-item prop="username">
                <el-input type="text" prefix-icon="fa fa-user" v-model="form2.username" placeholder="账号" clearable></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="text" prefix-icon="fa fa-unlock-alt" v-model="form2.password" placeholder="密码" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click.native.prevent="handleSubmit">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { Login } from '@/api/api'
export default {
    data () {
        return {
            form2: {
                username: '',
                password: ''
            },
            rules2: {
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        handleSubmit() {
            this.$refs.form2.validate(valid => {
                if(valid) {
                    let para = { username: this.form2.username, password: this.form2.password }
                    Login(para).then(res => {
                        let { msg, code } = res;
                        console.log(msg, code)
                        if(code !== 200 ) {
                            this.$message.error(msg)
                        } else {
                            this.$message.success(msg);
                            this.$router.push({ path: '/'})
                        }
                    })
                } else {
                    return false;
                }
            });
        }
    }
}
</script>
<style lang="scss">
    .login {
       width: 100%;
       height: 100%;
       display: flex;
       justify-content: center;
       align-items: center;
    }
    .login2 {
        height: 100%;
        width: 60%;
    }
</style>


    原文作者:Graycrr
    原文地址: https://segmentfault.com/a/1190000015777163
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞