vue 项目中使用echarts起步
在组件<mychart.vue>中:
<template>
<div>
<div ref="mychart"></div>
</div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
draw() {
let echarts = require('echarts')
// 基于准备好的dom,初始化echarts实例
let myChart = this.$refs.mychart
if (myChart) {
let echartInit = echarts.init(myChart)
// 绘制图表
echartInit.setOption({
title: {
text: "ECharts 入门示例"
},
tooltip: {},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20]
}
]
});
} else {
console.log('myChart 为空');
}
}
},
mounted() {
this.draw();
}
};
</script>
<style>
#mychart {
height: 500px;
}
</style>
值得注意的是,在 vue 项目中不推荐对 dom 的直接操作,例如
document.getElementId('my_div')
而应该使用 ref 引用来代替之:
<div ref = "myDiv"></div>
...
<script>
...
let myDiv = this.$refs.myDiv
</script>