mock.js:生成随机数,拦截Ajax请求模拟后端接口返回的数据完成交互功能
1、安装mock.js
npm install mockjs
2、在mian.js里导入
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import './mock' // 推荐下面
if (process.env.NODE_ENV === 'development') { // 在开发环境中使用
require('./mock')
// 或者 import './mock'
}
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts
Vue.use(ElementUI)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3、在src目录里新建一个mock文件夹,然后在里面再创建index.js
const Mock = require('mockjs')
// 或者 import Mock from 'mockjs'
// 设置mock接口数据返回所需时间
Mock.setup({
timeout: 600
})
// 接口,第一个参数url,第二个参数请求类型,第三个参数响应回调
Mock.mock('/api/classInfo', 'get', res => {
return {
responseCode: '10001',
responseMsg: 'success',
data: [
// 写自己所要的数据格式
{ "name": "语文", "value": 9241, "ratio": 91.96 },
{ "name": "数学", "value": 308, "ratio": 3.06 },
{ "name": "英语", "value": 160, "ratio": 1.59 },
{ "name": "历史", "value": 122, "ratio": 1.21 },
{ "name": "地理", "value": 50, "ratio": 0.5 },
{ "name": "政治", "value": 168, "ratio": 1.67 }
]
}
})
// 打印当前Mock的版本号
console.log(Mock.version)
4、在页面调用写好的mock接口
mounted () {
// 方法一
axios.get('/api/classInfo').then(res => {
console.log('方法一:mock模拟的数据', res)
})
// 方法二
// 注意 classInfoApi() 为封装过后的接口请求方法
classInfoApi().then(res => {
console.log('方法二:mock模拟的数据', res)
}).catch((error) => {
console.log(error)
})
// 方法三
this.classInfo()
},
methods: {
// 方法三
async classInfo () {
let res = await classInfoApi()
console.log('方法三:mock模拟的数据', res)
}
}
若对你有所帮助,请点个赞👍,若有疑问,请在评论留言