一 axios二次封装
安装axios:
npm i axios
在vue脚手架的main.js全局引入(axios不是插件,不能使用Vue.use方法引入)
import http from "axios";
Vue.prototype.$http = http;
创建api/config/index.js 文件:
export default{
baseUrl:{
dev:'/api/',//开发环境
pro:'',//生产环境
}
}
在api/axios.js封装axios类:
import axios from 'axios'
import config from '../config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
class HttpRequest {
constructor (baseUrl) {
this.baseUrl = baseUrl
}
getInsideConfig() {
const config = {
baseUrl: this.baseUrl,
header: {}
}
return config
}
interceptors (instance) {
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
instance.interceptors.response.use(function (response) {
// 对响应数据做点什么
console.log(response)
return response;
}, function (error) {
console.log(error, 'error')
// 对响应错误做点什么
return Promise.reject(error);
});
}
request(options) {
const instance = axios.create()
options = { ...this.getInsideConfig(), ...options }
this.interceptors(instance)
return instance(options)
}
}
export default new HttpRequest(baseUrl)
创建data.js:
import axios from './axios'
export const getMenu=(param)=>{
return axios.request({
url:'/permission/getMenu',
method:'post',
data:param
})
}
二 mock数据模拟
(1)安装
npm i mock
(2)在api/mockServerData/home.js添加
// mock数据模拟
import Mock from 'mockjs'
// 图表数据
let List = []
export default {
getStatisticalData: () => {
//Mock.Random.float 产生随机数100到8000之间 保留小数 最小0位 最大0位
for (let i = 0; i < 7; i++) {
List.push(
Mock.mock({
苹果: Mock.Random.float(100, 8000, 0, 0),
vivo: Mock.Random.float(100, 8000, 0, 0),
oppo: Mock.Random.float(100, 8000, 0, 0),
魅族: Mock.Random.float(100, 8000, 0, 0),
三星: Mock.Random.float(100, 8000, 0, 0),
小米: Mock.Random.float(100, 8000, 0, 0)
})
)
}
return {
code: 20000,
data: {
// 饼图
videoData: [
{
name: '小米',
value: 2999
},
{
name: '苹果',
value: 5999
},
{
name: 'vivo',
value: 1500
},
{
name: 'oppo',
value: 1999
},
{
name: '魅族',
value: 2200
},
{
name: '三星',
value: 4500
}
],
// 柱状图
userData: [
{
date: '周一',
new: 5,
active: 200
},
{
date: '周二',
new: 10,
active: 500
},
{
date: '周三',
new: 12,
active: 550
},
{
date: '周四',
new: 60,
active: 800
},
{
date: '周五',
new: 65,
active: 550
},
{
date: '周六',
new: 53,
active: 770
},
{
date: '周日',
new: 33,
active: 170
}
],
// 折线图
orderData: {
date: ['20191001', '20191002', '20191003', '20191004', '20191005', '20191006', '20191007'],
data: List
},
}
}
}
}
在api/mock.js添加:
import Mock from 'mockjs'
import homeApi from './mockServerData/home'
// 拦截器规则 url地址 回调函数返回具体的数据
Mock.mock('/home/getData',homeApi.getStatisticalData)
(3)在main.js中进行引入
import "../api/mock.js";
三 使用
(1)在data.js添加如下代码:
export const getData=()=>{
return axios.request({
url:'/home/getData',
methods:'get',
})
}
(2)在public/index.html页面引入echarts
<script src="./js/echarts.min.js"></script>
(3)安装element-ui(全局引入)
终端输入:
npm i element-ui -s
在main.js加上下段代码 :
import ElementUI from 'element-ui'
import "element-ui/lib/theme-chalk/index.css";
Vue.use(ElementUI)
(4)views/home/index.vue页面:
<template>
<el-card style="height:280px">
<div style="height:280px" ref="echarts"></div>
</el-card>
<div class="graph">
<el-card style="height:260px">
<div style="height:240px" ref="userEcharts"></div>
</el-card>
<el-card style="height:260px">
<div style="height:240px" ref="videoEcharts"></div>
</el-card>
</div>
</template>
<script>
import {getData} from '../../../api/data.js'
export default {
name:'home',
mounted(){
getData().then(res=>{
const { code, data } = res.data
if (code === 20000) {
const order=data.orderData
const xData=order.date
const keyArray=Object.keys(order.data[0])//["苹果","vivo","oppo"]
const series=[]
keyArray.forEach(key=>{
series.push({
name:key,
data:order.data.map(item=>item[key]),
type:'line'
})
})
const option={
xAxis:{
data:xData
},
yAxis:{},
legend:{
data:keyArray
},
series
}
const E=echarts.init(this.$refs.echarts)
E.setOption(option)
//用户图
const userOption={
legend:{
//图例文字颜色
textStyle:{
color:"#333",
}
},
grid:{
left:"20%"
},
tooltip:{
trigger:"axis",
},
xAxis:{
type:"category",//类目轴
data:data.userData.map(item=>item.date),
// 坐标轴线
axisLine:{
lineStyle:{
color:"#17b3a3"
}
},
// 坐标轴刻度标签的相关设置
axisLable:{
/**interval:
* 坐标轴刻度标签的显示间隔,在类目轴中有效。
默认会采用标签不重叠的策略间隔显示标签。
可以设置成 0 强制显示所有标签。
如果设置为 1,表示『隔一个标签显示一个标签』
,如果值为 2,表示隔两个标签显示一个标签,以此类推。 */
interval:0,
color:"#333"
}
},
yAxis:[
{
type:"value",
axisLine:{
lineStyle:{
color:"#17b3a3"
}
}
}
],
color:["#2ec7c9","#b6a2de"],
series:[
{
name:'新增用户',
data:data.userData.map(item=>item.new),
type:'bar'
},
{
name:'活跃用户',
data:data.userData.map(item=>item.active),
type:'bar'
}
]
}
const U=echarts.init(this.$refs.userEcharts)
U.setOption(userOption)
const videoOption={
tooltip:{
trigger:"item"
},
color:[
"#0f78f4",
"#dd536b",
"#9462e5",
"#a6a6a6",
"#e1bb22",
"#39c362",
"#3ed1cf",
],
series:[{
data:data.videoData,
type:'pie',
}]
}
const V=echarts.init(this.$refs.videoEcharts)
V.setOption(videoOption)
//根据窗口的大小变动图表
window.onresize=function(){
E.resize(),
U.resize(),
V.resize()
}
}
})
}
}
</script>
<style>
</style>
实现效果图:
四 封装Echarts
(1)在components文件夹创建Echarts.vue,并在上面添加如下代码
<template>
<div ref="echart"></div>
</template>
<script>
export default {
/*折线图和柱形图代码基本结构一致,而饼图没有坐标轴,所以可以分为两类*/
props: {
isAxisChart: {
type: Boolean,
default: true
},
chartData: {
type: Object,
default() {
return {
xData: [],
series: []
}
}
}
},
watch: {
chartData: {
handler: function () {
this.initChart()
},
deep: true
},
},
methods: {
initChart() {
this.initChartData()
if (this.echart) {
this.echart.setOption(this.options)
window.onresize=function(){
this.echart.resize()
}
} else {
this.echart = echarts.init(this.$refs.echart)
this.echart.setOption(this.options)
window.onresize=function(){
this.echart.resize()
}
}
},
initChartData() {
if (this.isAxisChart) {
this.axisOption.xAxis.data = this.chartData.xData
this.axisOption.series = this.chartData.series
} else {
this.normalOption.series = this.chartData.series
}
}
},
data() {
return {
axisOption: {
// 图例文字颜色
legend:{},
textStyle: {
color: "#333",
}
,
grid: {
left: "20%",
},
// 提示框
tooltip: {
trigger: "axis",
},
xAxis: {
type: "category", // 类目轴
data: [],
axisLine: {
lineStyle: {
color: "#17b3a3",
},
},
axisLabel: {
interval: 0,
color: "#333",
},
},
yAxis: [
{
type: "value",
axisLine: {
lineStyle: {
color: "#17b3a3",
},
},
},
],
color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
series: [],
},
normalOption: {
tooltip: {
trigger: "item",
},
color: [
"#0f78f4",
"#dd536b",
"#9462e5",
"#a6a6a6",
"#e1bb22",
"#39c362",
"#3ed1cf",
],
series: [],
},
echart: null
}
},
computed: {
options () {
return this.isAxisChart ? this.axisOption : this.normalOption
}
}
}
</script>
(2)views/home/index.vue修改代码步骤
1)引入
import Echart from '../../components/Echarts.vue'
2)修改如红方框所示
3)添加如下红方框代码
4)
折线图代码:
柱状图代码:
饼图代码: