First use vue-cli scaffolding to build a project, followed by the operations of the project creation
Installation dependencies
npm install mockjs --save
The directory structure is as follows
mock directory section
The mock folder is used to store simulation logic and data. mock/index.js is an entry file used to store all mock entries. It needs to be directly imported in main.js. import '@/mock/index.js'
If there are some interfaces that need to be simulated later, some do not Simulation, you can write judgment in this mock entry.
import {
login } from './login';
login()
mock/login.js is the logic of login
import Mock from 'mockjs';
// 设置延时时间
Mock.setup({
timeout: "300-600",
});
export function login() {
let menu = Mock.mock({
"menu|10": [
{
id: "@id",
path: "@word(4)/@word(4)",
meta: {
title: "@cword(5)",
icon: Mock.Random.image("200x100", "#4A7BF7", "Hello"),
},
name: "@word(4)",
},
],
});
//实现对拦截到请求的处理
Mock.mock("api/login", "post", req => {
let {
username, password } = JSON.parse(req.body);
if (username == "admin" && password == "123456") {
return {
code: 1,
msg: "成功",
token: "teosdsfdfdksdfs232323",
menu,
};
} else {
return {
code: 0,
msg: "账号密码错误",
};
}
});
}
api directory part
The api directory is the normal way of writing when the mock is not used, and there is no change. Here I just implement a simulated login logic, the following isapi/login.js
import request from "@/plugins/axios";
export function login(data) {
return request({
url: "api/login",
method: "post",
data
});
}
Use in login page
<template>
<div>
<h3>登录</h3>
<el-form :model="form" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="form.username"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="form.password"></el-input>
</el-form-item>
</el-form>
<el-button :loading="loading" type="success" @click="login">登录</el-button>
</div>
</template>
<script>
import {
login} from '@/api/login'
export default {
data() {
return {
loading: false,
form: {
username:'',
password:''
}
}
},
methods:{
login(){
this.loading = true;
login(this.form).then(res=>{
console.log(res)
this.loading = false;
if(res.code == 1){
localStorage.setItem('TOKEN',res.token)
this.$notify({
title: res.msg,
type: 'success'
})
this.$router.push({
name:'Home'})
}else{
this.$notify({
title: res.msg,
type:'warning'
})
}
})
}
}
}
</script>
<style lang="scss" scoped>
.el-form{
width:300px;
margin:70px auto 10px auto;
}
.el-input{
width:200px;
}
</style>
effect