echarts图表切换
一.创建vue脚手架
二.安装echarts npm install echarts --save
三.在components中创建myEcharts.vue文件夹,并复制以下代码到myEcharts.vue文件中
<template>
<div :id="uuid" style="width:600px;height:400px;"></div>
</template>
<script>
import * as echarts from "echarts";
// 以时间戳的形式来形成动态 id
const idGen = () => {
return new Date().getTime();
};
export default {
data() {
return {
uuid: null,
myChart: null,
};
},
props: {
options: {
type: Object,
default: null,
},
},
computed: {
style() {
return {
height: this.height,
width: this.width,
};
},
},
watch: {
options() {
if (this.myChart) {
this.myChart.setOption(this.options, {
// motMerge 可防止改变echarts图表时颜色也被改变
notMerge: true
});
}
},
},
created() {
this.uuid = idGen();
},
mounted() {
// 基于准备好的dom,初始化echarts实例
this.myChart = echarts.init(document.getElementById(this.uuid));
// 指定图表的配置项和数据
// 使用刚指定的配置项和数据显示图表。
this.myChart.setOption(this.options);
},
};
</script>
<style>
</style>
四.在app.vue 文件下引入,注册,使用 myEcharts 文件,复制以下代码到app.vue中
<template>
<div id="app">
<my-echarts :width="width" :options="options"></my-echarts>
<button @click="changeEcharts">改变图表</button>
</div>
</template>
<script>
import myEcharts from "./components/myEcharts.vue";
import { options1, options2 } from "@/options";
export default {
name: "App",
components: {
myEcharts,
},
data() {
return {
options: options1, // 设置默认值为options1
};
},
methods: {
changeEcharts() {
if (this.options == options1) {
this.options = options2;
} else {
this.options = options1;
}
},
},
};
</script>
<style>
</style>
五.写入数据,创建一个option.js文件夹,并复制以下代码到option.js文件夹中
export const options1 = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ["衬衫", "羊毛1衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
export const options2 = {
color:['red'],
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ["衬衫", "羊毛1衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [50, 27, 64, 100, 100, 200]
}]
}