VUE-cli使用-Echarts柱状表使用以及注意事项(v-if v-show的问题)

安装eharts
​​​​​​​npm install echarts -S

在main.js全局引入

import echarts from 'echarts'
Vue.prototype.$echarts = echarts

在需要用的组件中创建标签

<div id="myChart"></div>

methods里面创建绘制图表方法以及图标配置

// 绘制图表
			drawLine() {
				// 基于准备好的dom,初始化echarts实例
				let myChart = this.$echarts.init(document.getElementById('myChart'))
				// 绘制图表
				myChart.setOption({
					grid: {
						top: '5%',
						left: '10%',
						bottom: '32.5%'
					},
					color: ['#f00'], //全局字体颜色
					textStyle: {
						fontSize: 12,
					},
					tooltip: {
						trigger: 'axis',
						confine: true,
						axisPointer: { // 坐标轴指示器,坐标轴触发有效
							type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
						},
					},
					legend: {
						show: false //提示
					},
					xAxis: {
						show: this.charsShow,
						data: this.productNamesList, //x轴数据 与y轴一一对应
						axisLabel: {
							interval: 0,
							rotate: 50, //旋转
							textStyle: {
								fontSize: 10,
							},
							formatter: function (val) {
								var relVal = '';
								relVal += val.substr(0, 5) + "…";
								return relVal;
							} //处理函数
						}
					},
					yAxis: {
						fontSize: 12,
						type: 'value',
						show: this.charsShow,
						axisLabel: {
							textStyle: {
								fontSize: 12 // 让字体变大
							},
						}
					},
					series: [{
						name: '销量',
						type: 'bar',
						data: this.productSalesCountList,
					}],
					dataZoom: [{
							type: 'slider',
							show: false,
							xAxisIndex: [0],
							start: 0,
							end: 60
						},
						{
							type: 'inside',
							xAxisIndex: [0],
							start: 0,
							end: 60
						},
					],
				});
			},

data设置一个示例数据,ajax同样

return {
				
				productNamesList: [
            '商品1', '商品2', '商品3', '商品4',
    ],
				productSalesCountList: [
    1,2,4,6

],
			
}

直接使用this.drawLine()方法即可绘制图表

注意事项:v-if对echarts会报错,因为使用this.drawLine()方法找不到需要渲染的DOM对象(v-if),v-show会影响图表的宽高,建议给图表加一个父级用v-if控制父级

	<div class="chart_box" v-if="charsShow">
		<div id="myChart">
		</div>
	</div>


	<div class="nullData nullpos" v-else>暂无相关数据</div> 
data(){
    return{
        nullDraw: false,
        charsShow: false
    }
}
	if (that.productNamesList.length > 0 && that.productSalesCountList.length > 0) {
								that.nullDraw=true
								that.charsShow = true;
								if (that.nullDraw == true) {
									this.$nextTick(
										function () {
											this.drawLine();
										}
									)
								}
							} else {
								console.log('首次加载如果没有数据不加载图表,如果有数据再加载图表,每次执行完毕设置nullDraw为false')
								that.nullDraw=false
								if (that.nullDraw == true) {
									this.$nextTick(
										function () {
											this.drawLine();
										}
									)
								}
								that.charsShow = false;
								that.nullDraw=false
							}

效果图

猜你喜欢

转载自blog.csdn.net/qinyongqaq/article/details/82787029