版本:"echarts": "^5.0.1"
cnpm i -S [email protected]
组件目录结构:
使用:
<!--menu1-->
<template>
<div>
<el-button @click="setData()">更新</el-button>
<LjEchart :options="options" width="600px"></LjEchart>
</div>
</template>
<script>
import LjEchart from "@/components/LjEchart/index.vue";
export default {
name: "",
components: {
LjEchart,
},
props: {},
data() {
return {
cdata: {
category: ["2015", "2016", "2017", "2018", "2019", "2020"],
barData: [120, 200, 150, 80, 70, 110, 130],
},
};
},
computed: {
options() {
return {
xAxis: {
type: "category",
data: this.cdata.category,
},
yAxis: {
type: "value",
},
series: [
{
data: this.cdata.barData,
type: "bar",
},
],
tooltip: {
trigger: "axis",
backgroundColor: "rgba(255,255,255,0.1)",
borderColor: "rgba(255,255,255,0.1)",
axisPointer: {
type: "shadow",
label: {
show: true,
backgroundColor: "#7B7DDC",
},
},
textStyle: {
color: "white",
},
},
};
},
},
methods: {
setData() {
this.cdata.category = ["2015", "2016", "2017", "2018", "2019", "2020"];
this.cdata.barData = [220, 100, 350, 280, 170, 310, 30];
},
},
};
</script>
<style lang="scss" scoped>
</style>
可以自定义主题:只需要传入属性theme即可。首先下载json格式的主题,如test.json,放在@/assets文件夹中。页面中导入主题 import testTheme from "@/assets/test.json",并赋值给属性myTheme:testTheme
<LjEchart :options="options" width="600px" :theme="myTheme"></LjEchart>
index.vue:
<template>
<div :style="{ height: height, width: width }" />
</template>
<script>
import theme from "./theme.json"; // 引入默认主题
import resizeMixins from "./utils/resizeMixins";
export default {
name: "echart",
mixins: [resizeMixins],
props: {
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "400px",
},
options: {
type: Object,
default: () => ({}),
},
theme: {
type: Object,
default: () => {
return theme;
},
},
},
data() {
return {
chart: null,
};
},
watch: {
options: {
handler(options) {
// 设置true清空echart缓存
this.chart.setOption(options, true);
},
deep: true,
},
},
mounted() {
this.$echarts.registerTheme("theme", this.theme); // 覆盖默认主题
this.initChart();
},
methods: {
initChart() {
// 初始化echart
this.chart = this.$echarts.init(this.$el, "theme");
this.chart.setOption(this.options, true);
},
},
};
</script>
utils/index.js:
/**
* @param {Function} fn 防抖函数
* @param {Number} delay 延迟时间
*/
export function debounce(fn, delay) {
var timer;
return function () {
var context = this;
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
utils/resizeMixins.js
// 混入代码 resize-mixins.js
import { debounce } from './index.js';
const resizeChartMethod = '$__resizeChartMethod';
export default {
data() {
// 在组件内部将图表 init 的引用映射到 chart 属性上
return {
chart: null,
};
},
created() {
window.addEventL