本文主要是介绍Vue项目中使用mockjs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、插件版本
"axios": "^0.27.2",
"vue": "^2.6.14",
"mockjs": "^1.1.0",
2、在vue-cli搭建的项目根目录下新建一个js文件:mocks/index.js
2.1 简单使用mockjs
// 引入mockjs
import Mock from 'mockjs';// 假数据
var menus = [{'menuId': 1,'menuName': '系统管理'},{'menuId': 2,'menuName': '用户管理'}
];// mock模拟的接口
Mock.mock('sys/menu/list', 'get', function () {return {code: 0,message: 'success',data: menus}
});
2.2 mock接口较多可按模块拆分
mocks/index.js
// 引入mockjs
import Mock from 'mockjs';// mock接口
import login from './api/login.js';
import config from './api/config.js';login.install(Mock);
config.install(Mock);
mocks/api/login.js
const users = [{ id: 1, username: 'admin', password: '123456', token: 'admin-token' },{ id: 2, username: 'common', password: '123456', token: 'common-token' }
];
export default {install(Mock) {Mock.mock('/login', 'post', function (data) {const userData = JSON.parse(data.body);var user = users.find(item => item.username === userData.username && item.password === userData.password);if(user) {return {code: 200,msg: 'success',token: user.token}} else {return {code: 500,msg: '用户不存在或密码错误',} }});Mock.mock('/getInfo', 'get', function () {return {code: 200,msg: 'success',data: {username: 'admin',role: 'system',}}});Mock.mock('/logout', 'get', function () {return {code: 200,msg: 'success',data: true}});}
}
mocks/api/config.js
export default {install(Mock) {Mock.mock('sys/config/getConfig', 'get', function () {return {code: 200,msg: 'success',data: {projectName: '管理平台',}}});}
}
3、在main.js中引入mock模拟接口
import Vue from 'vue';
import App from './App.vue';
import router from './router/index.js';Vue.config.productionTip = false// 引入mock数据
require('../mocks/index.js');new Vue({render: h => h(App),router
}).$mount('#app')
4、使用mock模拟接口
<template><div>vue-cli搭建的项目中使用mock数据</div>
</template><script>
import axios from 'axios';export default {name: 'mock',mounted () {this.getData();},methods: {getData () {axios.get('sys/menu/list').then(res => {console.log(res)}).catch(error => {console.log(error)})}}
}
</script>
控制台输出结果:
这篇关于Vue项目中使用mockjs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!