vue進階3 - Mock.js(生成隨機數據,模擬Ajax請求)

1、安裝

1.安裝mock、axioscss

npm install mockjs axios

二、安裝axios-mock-adaptervue

axios-mock-adapter是axios與mock配置器,是axios的模擬調試器
npm install axios-mock-adapter --save-dev

2、建立mock文件

1.新建src/mock/data/user.js,生成隨機數據ios

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請求的接口,生成並返回模擬數據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的內容,而且導出npm

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

4.打開src/main.js, 引入mock,全局加載mock並執行初始化函數axios

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

3、封裝api函數

1.新建src/api/api.js,把全部接口都寫到一個文件裏面,封裝成一個個函數,便於修改與管理api

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.jsdom

import * as api from './api';

export default api;

4、調用接口

新建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>
相關文章
相關標籤/搜索