vue 项目中使用 axios + mockjs实现请求的拦截和数据模拟
程序员文章站
2022-03-18 13:47:52
...
先用vue-cli脚手架建一个项目,后面是项目创建完成的操作
安装依赖
npm install mockjs --save
目录结构如下
mock目录部分
mock文件夹用来存放模拟的逻辑和数据,mock/index.js是一个入口文件,用来存放所有的mock入口,需要在main.js中直接引入import '@/mock/index.js'
,如果后期有一部分接口需要模拟,有些不需要模拟,可以在这个mock入口里写判断。
import { login } from './login';
login()
mock/login.js是登录的逻辑
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目录部分
api目录下就是正常不用mock时候的写法,没有变化,这里我只是实现一个模拟登录的逻辑,下面是api/login.js
import request from "@/plugins/axios";
export function login(data) {
return request({
url: "api/login",
method: "post",
data
});
}
登录页面中使用
<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>