echarts学习笔记(vue项目中使用)

1、vue整合echarts

npm install echarts --save

创建components

<template>
    <div id="main" :style="{width: '1400px', height: '400px'}"></div>
</template>
<<script>
import * as echarts from 'echarts';
export default {
    name: 'BarDemo',
    watch: {
        data:{
            handler(val, oldVal){
                this.init();
            },
            deep:true //true 深度监听
        },
    },
    data () {
        return {
            data: [120, 200, 150, 80, 70, 110, 130],
            //x轴刻度
            xAxisData: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        }
    },
    mounted() {
        this.init()
    },
    methods: {
        init(){
            var chartDom = document.getElementById('main');
            var myChart = echarts.init(chartDom);
            var option;

            option = {
            //竖着的柱状图
            // xAxis: {
            //     type: 'category',
            //     data: this.xAxisData
            // },
            // yAxis: {
            //     type: 'value'
            // },
            //横着的柱状图
            yAxis: {
                type: 'category',
                data: this.xAxisData
            },
            xAxis: {
                type: 'value'
            },
            series: [
                {
                data: this.data,
                type: 'bar'
                }
            ]
            };

            option && myChart.setOption(option);

        }
    },
}
</script>

注意这里要用mounted,使用created报错:Error: Initialize failed: invalid dom.

created这时候还只是创建了实例,但模板还没挂载完成

在index中添加

//导入组件
import EchartsDemo from '@/components/test/EchartsDemo'
//添加routes
	{
      path: '/EchartsDemo',
      name: 'EchartsDemo',
      component: EchartsDemo
    }

在其他页面使用router-link跳转即可

<router-link to="/EchartsDemo">echarts柱状图</router-link>

2、组件化封装echarts模板

2.1、定义饼图模板组件

模板组件提供props属性opt,当其他页面使用模板组件对opt绑定赋值时会被watch监听,执行optHandler后动态渲染图表,echarts的setOption方法使用了属性合并。

<template>
  <div ref="chart" :style="{ width: '1400px', height: '400px' }"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
  name: "PieChart",
  props: {
    opt: {
      type: Object,
      default() {
        return {};
      }
    },
  },
  watch: {
    opt: {
      deep: true,
      handler(opt) {
        this.optHandler(opt)
      }
    },
  },
  data() {
    return {
      chart: null,
      option: {
        legend: {
          show: true
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            itemStyle: {
              borderRadius: 5
            },
            data: []
          }
        ],
        tooltip: {
          trigger: "item"
        }
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 初始化
      this.chart = echarts.init(this.$refs.chart);
      this.chart.setOption(this.option);
    },
    optHandler(option) {
      if (Object.keys(option).length > 0) {
        this.chart.setOption(option)
      }
    },
  }
};
</script>

由于echarts的setOption方法对option进行了属性合并,所以外部使用option进行赋值重新渲染时,只需要修改(或添加)option中对应的属性即可,需要注意的是,赋值使用的是option.series[0].data,在data()中声明时也需要声明到这一级别,否则模板组件中会监听不到数据变化,测试代码如下:

<template>
  <pie-chart :opt="option"></pie-chart>
</template>
<script>
import PieChart from "@/components/echarts/PieChart";
export default {
  name: "PieTest",
  components: {
    PieChart
  },
  data() {
    return {
      option: {
        series: [
          {
            data: []
          }
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.option.series[0].data = [
          { value: 1048, name: "Search Engine" },
          { value: 735, name: "Direct" },
          { value: 580, name: "Email" },
          { value: 484, name: "Union Ads" },
          { value: 300, name: "Video Ads" }
        ];
    }
  }
};
</script>

2.2、定义柱状图模板组件

option也可以不在data()中定义

<template>
  <div ref="chart" :style="{ width: '1400px', height: '400px' }"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
  name: "PieChart",
  props: {
    opt: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  watch: {
    opt: {
      deep: true,
      handler(opt) {
        this.optHandler(opt);
      }
    }
  },
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 初始化
      this.chart = echarts.init(this.$refs.chart);
    },
    optHandler(option) {
      if (Object.keys(option).length > 0) {
        this.chart.clear()
        this.chart.setOption({
        xAxis: {
          type: "category",
          data: option.yAxis.data
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            data: option.series[0].data,
            type: "bar"
          }
        ]
      });
      }
    }
  }
};
</script>

测试代码:

<template>
  <bar-chart :opt="option"></bar-chart>
</template>
<script>
import BarChart from "@/components/echarts/BarChart";
export default {
  name: "BarTest",
  components: {
    BarChart
  },
  data() {
    return {
      option: {
        yAxis: {
            data: []
        },
        series: [
          {
            data: []
          }
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.option.series[0].data = [120, 200, 150, 80, 70, 110, 130]
      this.option.yAxis.data =  ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    }
  }
};
</script>

2.3、定义折线图模板组件

侦听器也可以用this.$watch的方式定义

<template>
  <div ref="chart" :style="{ width: '1400px', height: '400px' }"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
  name: "StackedLineChart",
  props: {
    opt: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 初始化
      this.chart = echarts.init(this.$refs.chart);
      this.$watch("opt", option => this.optHandler(option), {
      immediate: true,
      deep: true
    })
    },
    optHandler(option) {
      if (Object.keys(option).length > 0) {
        this.chart.clear();
        this.chart.setOption({
          title: {
            text: "Stacked Line"
          },
          tooltip: {
            trigger: "axis"
          },
          legend: {
            data: ["Email", "Union Ads", "Video Ads", "Direct", "Search Engine"]
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: option.xAxis.data
          },
          yAxis: {
            type: "value"
          },
          series: option.series
        });
      }
    }
  }
};
</script>

测试代码:

<template>
  <stacked-line-chart :opt="option"></stacked-line-chart>
</template>
<script>
import StackedLineChart from "@/components/echarts/StackedLineChart";
export default {
  name: "StackedLineTest",
  components: {
    StackedLineChart
  },
  data() {
    return {
      option: {
        xAxis: {
          data: []
        },
        series: []
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.option.series = [
        {
          name: "Email",
          type: "line",
          stack: "Total",
          data: [120, 132, 101, 134, 90, 230, 210]
        },
        {
          name: "Union Ads",
          type: "line",
          stack: "Total",
          data: [220, 182, 191, 234, 290, 330, 310]
        },
        {
          name: "Video Ads",
          type: "line",
          stack: "Total",
          data: [150, 232, 201, 154, 190, 330, 410]
        },
        {
          name: "Direct",
          type: "line",
          stack: "Total",
          data: [320, 332, 301, 334, 390, 330, 320]
        },
        {
          name: "Search Engine",
          type: "line",
          stack: "Total",
          data: [820, 932, 901, 934, 1290, 1330, 1320]
        }
      ];
      this.option.xAxis.data = [
        "Mon",
        "Tue",
        "Wed",
        "Thu",
        "Fri",
        "Sat",
        "Sun"
      ];
    }
  }
};
</script>

2.4、定义仪表盘模板组件

<template>
  <div ref="chart" :style="{ width: '1400px', height: '400px' }"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
  name: "PieChart",
  props: {
    opt: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  watch: {
    opt: {
      deep: true,
      handler(opt) {
        this.optHandler(opt);
      }
    }
  },
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 初始化
      this.chart = echarts.init(this.$refs.chart);
    },
    optHandler(option) {
      if (Object.keys(option).length > 0) {
        this.chart.clear()
        this.chart.setOption({
            tooltip: {
                formatter: '{a} <br/>{b} : {c}%'
            },
            series: [
                {
                name: 'Pressure',
                type: 'gauge',
                detail: {
                    formatter: '{value}'
                },
                data: option.series[0].data
                }
            ]
            });
      }
    }
  }
};
</script>

测试代码:

<template>
  <gauge-chart :opt="option"></gauge-chart>
</template>
<script>
import GaugeChart from "@/components/echarts/GaugeChart";
export default {
  name: "GaugeTest",
  components: {
    GaugeChart
  },
  data() {
    return {
      option: {
        series: [
          {
            data: []
          }
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.option.series[0].data = [{
                value: 50,
                name: 'SCORE'
            }]
    }
  }
};
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用echartsvue项目可以通过以下步骤: 1. 安装echarts 可以通过npm或yarn来安装echarts ``` npm install echarts --save ``` ``` yarn add echarts ``` 2. 引入echarts 在需要使用echartsvue组件,通过import语句引入echarts: ``` import echarts from 'echarts' ``` 3. 创建echarts表 在vue组件,可以通过以下方式创建echarts表: ``` <template> <div class="chart-container" ref="chart"></div> </template> <script> import echarts from 'echarts' export default { mounted() { const chart = echarts.init(this.$refs.chart) chart.setOption({ // echarts配置 }) } } </script> ``` 在上面的代码,我们通过ref属性引用了一个div元素,然后通过this.$refs.chart获取到了这个div元素,在mounted钩子函数通过echarts.init方法初始化了一个echarts实例,最后通过chart.setOption方法设置了echarts的配置。 4. 实时数据更新 如果需要实现实时数据更新,可以通过watch监听数据的变化,然后在回调函数更新echarts表: ``` <template> <div class="chart-container" ref="chart"></div> </template> <script> import echarts from 'echarts' export default { data() { return { chartData: [] } }, mounted() { const chart = echarts.init(this.$refs.chart) this.setChartOption(chart, this.chartData) }, watch: { chartData: { handler(newData) { const chart = echarts.init(this.$refs.chart) this.setChartOption(chart, newData) }, deep: true } }, methods: { setChartOption(chart, data) { chart.setOption({ // echarts配置 series: [ { data: data } ] }) } } } </script> ``` 在上面的代码,我们通过watch监听了chartData的变化,在回调函数重新创建了一个echarts实例,并调用了setChartOption方法来更新echarts表。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值