当前位置:   article > 正文

Vue3自定义Echars组件附带全局配置

Vue3自定义Echars组件附带全局配置
  1. <template>
  2. <div ref="chart" :id="id" :class="className" :style="{ height: height, width: width }"></div>
  3. </template>
  4. <script setup>
  5. import { ref, reactive, toRefs, onMounted, onBeforeUnmount,watch } from 'vue'
  6. import * as echarts from 'echarts';
  7. // 传递参数
  8. const props = defineProps({
  9. className: {
  10. type: String,
  11. default: 'chart'
  12. },
  13. id: {
  14. type: String,
  15. default: 'chart'
  16. },
  17. width: {
  18. type: String,
  19. default: '100%'
  20. },
  21. height: {
  22. type: String,
  23. default: '280px'
  24. },
  25. options: {
  26. type: Object,
  27. default: () => { }
  28. }
  29. })
  30. const chart = ref(null);
  31. const createChart = () => {
  32. const myChart = echarts.init(chart.value);
  33. chart.value = echarts.init(chart.value, 'tdTheme')
  34. myChart.setOption(props.options,true);
  35. // chart.value.setOption(props.options, true)
  36. window.addEventListener("resize", () => {
  37. chart.value.resize()
  38. })
  39. };
  40. watch(() => props.options, (options) => {
  41. if (chart.value) {
  42. // 设置true清空echart缓存
  43. chart.value.setOption(options, true)
  44. }
  45. }, { deep: true })
  46. onMounted(() => {
  47. createChart();
  48. });
  49. onBeforeUnmount(() => {
  50. window.removeEventListener("resize", () => {
  51. chart.value.resize()
  52. })
  53. chart.value.dispose()
  54. chart.value = null
  55. })
  56. </script>
  1. import Echart from './components/echart/index.vue'
  2. import echarts from 'echarts'
  3. const app = createApp(App)
  4. // 将echarts挂载到全局对象上
  5. app.config.globalProperties.$echarts = echarts
  6. // 注册全局组件
  7. app.component('Echart', Echart)

案列

  1. <template>
  2. <div ref="chart" style="width: 600px; height: 400px;"></div>
  3. </template>
  4. <script setup>
  5. import { ref, onMounted } from 'vue';
  6. import * as echarts from 'echarts';
  7. const chart = ref(null);
  8. const createChart = () => {
  9. const myChart = echarts.init(chart.value);
  10. myChart.setOption({
  11. xAxis: {
  12. type: 'category',
  13. data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  14. },
  15. yAxis: {
  16. type: 'value'
  17. },
  18. series: [{
  19. data: [120, 200, 150, 80, 70, 110, 130],
  20. type: 'bar'
  21. }]
  22. });
  23. };
  24. onMounted(() => {
  25. createChart();
  26. });
  27. </script>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/215372
推荐阅读
相关标签
  

闽ICP备14008679号