echarts封装

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]
  }]
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咸鱼!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值