1.引入mock 和 axios
# 在项目中安装mock.js
npm install mockjs
#在项目中安装axios
npm install axios --save
2.在项目中新建mock文件夹里再建 index.js 和 mock.js 文件
3.在mock.js中自定义模拟数据4.44
//引入mock.js
import Mock from 'mockjs'
//随机生成数据
const Random = Mock.Random;
// 创建模拟数据
function creatGetMock() {
const getMock = Mock.mock({
//随机生成4个brandOne数组
'brandOne|4': [{
name: "@cname()",//随机生成中文名字
age: "@natural(2, 40)"//随机生成年龄2-4o之间
}],
})
return getMock
}
// 将模拟好的数据输出出去;
export {creatGetMock}
4.在index.js中
import Mock from 'mockjs'
import{creatGetMock,creatGetMockT}from './mock'
//设置延迟(需要的话可以加上)
// Mock.setup({
// timeout:'3000-5000'
// })
Mock.mock(/\/api\/mock(|\?\S*)$/, 'get', creatGetMock)
5.在main.js中引入
// 引入axios
import axios from 'axios'
// 在vue项目中 axios中无法直接使用vue.use() 所以将axios直接添加到Vue的原型上
Vue.prototype.axios = axios
// 设置为 false 以阻止 vue 在启动时生成生产提示。
Vue.config.productionTip = false
// 引入设置好的mock, 用于拦截请求
import './views/dashboard/mock/index'
6.在自己项目中api里设置方法获取模拟数据
// import request from '@/utils/request'
// //引入资源请求插件
import axios from 'axios'
//
// 全局引用了这里加上会报错
// this.axios = axios
export function mockList (data) {
return axios.get('/api/mock', {
data
})
}
7.前台页面调用接口获取模拟数据
在vue页面引入接口
import {mockList} from '@/api/qkjjsgl/index'
8.给echart赋值
data
<template>
<div :class="className" :style="{height:height,width:width}"/>
</template>
<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {mockList} from '@/api/qkjjsgl/index'
const animationDuration = 6000
export default {
mixins: [resize],
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '300px'
}
},
data() {
return {
chart: null,
mockListArray: [],
nameArr: [],
ageArr: []
}
},
created() {
//页面打开直接调用获取模拟数据
this.getMockList();
},
mounted() {
this.$nextTick(() => {
this.initChart(this.nameArr,this.ageArr);
})
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
methods: {
getMockList() {
mockList().then(response => {
this.mockListArray = response.data.brandOne;
//获取到模拟数据数组 this.mockListArray
this.mockListArray.forEach((el) => {
//循环遍历出X轴的name赋值给nameArr
this.nameArr.push(el.name);
//循环遍历出Y轴的age赋值给ageArr
this.ageArr.push(el.age);
})
//方法传参
this.initChart(this.nameArr, this.ageArr)
})
},
//获取到nameArr数组(X轴)和ageArr数组(Y轴)
initChart(nameArr,ageArr) {
this.chart = echarts.init(this.$el, 'macarons');
this.chart.setOption({
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
top: 10,
left: '2%',
right: '2%',
bottom: '3%',
containLabel: true
},
legend: {
data: ['sales']
},
xAxis: {
// data: ['Shirts', 'Cardigans', 'Chiffons', 'Pants', 'Heels', 'Socks']
//赋值
data: nameArr
},
yAxis: {},
series: [{
name: 'sales',
type: 'bar',
//data: [20, 36, 10, 10, 20]
//赋值
data: ageArr
}]
})
}
}
}
</script>
9.页面效果
完成!!!