首页 前端知识 vue3中封装echarts

vue3中封装echarts

2024-04-15 21:04:50 前端知识 前端哥 484 557 我要收藏

子组件

<template>
  <div :id="uid" :style="myStyle"></div>
</template>
<script setup>
import { onMounted, onBeforeMount, ref, defineProps, onBeforeUnmount, onUnmounted } from 'vue';
import * as echarts from 'echarts';
// 因为是封装的组件,会多次调用,id不能重复,要在初始化之前写,不然会报错dom为定义
let uid = ref('');
onBeforeMount(() => {
  uid.value = `echarts-uid-${parseInt((Math.random() * 1000000).toString())}`;
});

onMounted(() => {
  let myChart = echarts.init(document.getElementById(uid.value));
  // 在template中可以直接取props中的值,但是在script中不行,因为script是在挂载之前执行的
  myChart.setOption(props.myOption, {
    notMerge: true, //不和之前的option合并
  });

  // 监听页面的大小
  window.addEventListener('resize', () => {
    setTimeout(() => {
      myChart?.resize({
        animation: {
          duration: 300,
        },
      });
    }, 300);
  });
});

const props = defineProps({
  myStyle: {
    type: Object,
    default: () => ({
      width: '100%',
      height: '100%',
    }),
  },
  myOption: {
    type: Object,
    default: () => ({}),
    required: true,
  },
});
</script>

父组件

<template>
  <div class="card">
    <current-echarts :myOption="chartLineData" :myStyle="{ width: '273px', height: '330px' }"></current-echarts>
  </div>
</template>
<script>
import CurrentEcharts from '../../../components/CurrentEcharts.vue';
import { onMounted, reactive, toRefs, getCurrentInstance, onBeforeUnmount, onUnmounted } from 'vue';

export default {
  name: 'ehartLine',
  components: {
    CurrentEcharts
  },
  props: {

  },
  setup(props) {
    const chartLineData = {
      series: [
        {
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          labelLine: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '30',
              fontWeight: 'bold'
            }
          },
          data: [
            { value: 335, name: 'A' },
            { value: 310, name: 'B' },
            { value: 234, name: 'C' },
            { value: 135, name: 'D' },
            { value: 1548, name: 'E' }
          ]
        }
      ]
    }
    onMounted(() => {
    })
    onUnmounted(() => {

    })
    return {
      chartLineData
    };
  },
};
</script>


<style lang="scss" scoped>
.card {
  background: #FFFFFF;
  opacity: 1;
  border: 1px solid #E7EBF2;
  border-radius: 5px;

  .title {
    font-size: 16px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #34383E;
    padding: 20px 25px 18px 0;
    border-bottom: 1px solid #EEF1F5;
  }
}
</style>
转载请注明出处或者链接地址:https://www.qianduange.cn//article/5004.html
标签
评论
发布的文章

用js生成小米商城

2024-04-27 21:04:59

网页汇率计算器vue代码

2024-04-26 13:04:44

Python读写Json文件

2024-04-23 22:04:19

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!