安装mock
npm install mockjs --save-dev
或者在ui中选择依赖
查看安装是否成功
进入package.json文件
配置mock
在src目录下新建mock文件夹,在mock文件夹下建立index.js
配置模拟请求数据
index.js
import Mock from 'mockjs'
const loginData = Mock.mock('http://localhost:8080/login','post',{
status:200,
content:{username:'admin',password:'admin'}
})
const homeTableData = Mock.mock('http://localhost:8080/home','get',{
status:200,
content:
[{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '张三',
address: '上海市普陀区金沙江路 1517 弄'
}, {
date: '2016-05-01',
name: '李四',
address: '上海市普陀区金沙江路 1519 弄'
}, {
date: '2016-05-03',
name: '赵高',
address: '上海市普陀区金沙江路 1516 弄'
}
]
})
export default {
loginData,
homeTableData
}
在main.js中引用mock
require('./mock/idnex');
import { createApp } from 'vue'
import App from './App.vue'
import router from "@/router/idnex";
import axios from "@/request/request";
import store from '@/store/index'
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
require('./mock/idnex');
let app= createApp(App);
app.use(ElementPlus).use(router).use(store).mount('#app')
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
app.config.globalProperties.$axios=axios;
配合axios发起请求
配置axios
安装就不在赘述啦,安装完之后在src下建立request文件夹,在下边建立request.js
request.js
import axios from "axios";
const Request = axios.create({
//本地请求地址
baseURL:'http://localhost:8080',
//请求超时设置
timeout: 2000
})
// 响应拦截器
Request.interceptors.response.use(
(res)=>{
if(res) {
return {
status: res.status,
data: res.data.content
}
}
}
);
//导出我们建立的axios实例模块,ES6 export用法
export default Request
在main.js中配置axios ,上边的main.js已经配置过
发起请求完成数据模拟
我这里用的是vuex中的actions,如果用别的方式也行,没有一定之规,好用就行
actions: {
login:({commit},params)=>{
request('/login',{
method:'post',
data:params
}).then((res)=>{
console.log(res)
if(res.status === 200){
// localStorage
localStorage.setItem("loginData",`username:${res.data.username} password: ${res.data.password}`);
commit('modifyLoginStatus',true);
}else{
commit('modifyLoginStatus',false);
}
})
},
getHomeData:({commit})=>{
request('/home').then((res)=>{
if(res.status === 200){
commit('modifyHomeData',res.data);
}else{
commit('modifyHomeData',[]);
}
})
}
},
登录数据模拟
查看结果