随身笔记
随身笔记

vue引入echarts

echars 5.0之前引入用

import echarts from 'echarts' //引入echarts

 

echars 5.0之后引入用

import * as echarts from 'echarts' //引入echarts

 

vue2 echarts组件

<template>
   <div>
     <div id="main" ref="mycharts" class="chatscss"></div>
   </div>
</template>

<script>
import echarts from 'echarts'  //引入echarts 4.8.0
export default {
  props:['sourceData'],
  name: "echart",
  data(){
    return{
      initmycharts:null
    }
  },
  mounted() {
    this.$nextTick(()=>{
      this.init()
    })
  },
  watch:{
    sourceData:{
      handler: function (val, oldVal) {
       this.init()
      }, //不要使用箭头函数,否则this无法指向vue对象
      deep: true  //遇到对象或者复合结构要开启深度监听,简单数组不需要开启
    },
  },
  methods:{
    init(){
      var chartDom = document.getElementById('main');
      this.initmycharts = echarts.init(chartDom);
      var option;

      option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.sourceData,//[150, 230, 224, 218, 135, 147, 260],
            type: 'line'
          }
        ]
      };

      option && this.initmycharts.setOption(option);
      window.addEventListener('resize', ()=>{
        this.initmycharts.resize()
      })
    }
  }
}
</script>

<style scoped>
  .chatscss{
    height: 400px;width: 100%
  }
</style>

 

调用:

<myecharts :sourceData="testData"></myecharts>

testData:[150, 230, 224, 218, 135, 147, 860],

mounted() {
    
  setTimeout(()=>{
    this.testData = [150, 230, 224, 218, 135, 147, 60]
  },2000)
  
}

 

 

vue3 组件

<template>
  <div id="main" class="mycharts" ref="mycharts"></div>
</template>

<script setup>
import * as echarts from 'echarts'; //引入 5.5.0
import {effectScope,computed,ref,watch,watchEffect,reactive,watchPostEffect,getCurrentScope,onScopeDispose,defineOptions,onMounted,nextTick} from 'vue'

const mycharts = ref(null)
var init = ()=>{

  var myChartdom = echarts.init(mycharts.value);
  var option = {
    title: {
      text: 'ECharts 入门示例'
    },
    tooltip: {},
    legend: {
      data:['销量']
    },
    xAxis: {
      data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
    },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }]
  };
  // 使用刚指定的配置项和数据显示图表。
  myChartdom.setOption(option);
  window.onresize = function () {
    //自适应大小, 不用的话不会自适应大小。
    myChartdom.resize();
  };


}

onMounted(()=>{
  init()
})

</script>

<style scoped>

</style>

 

调用:

<echarts></echarts>

<script setup>
import echarts from './echarts.vue'
</script>

 

 

 

 

 

 

随身笔记

vue引入echarts
echars 5.0之前引入用 import echarts from 'echarts' //引入echarts   echars 5.0之后引入用 import * as echarts from 'echarts' //引入echarts   vue2 echarts组…
扫描二维码继续阅读
2024-03-14