vue3封裝Echarts為Vue組件


一、創建Charts.vue組件

<template>
  <div class="container" ref="container"></div>
</template>

<script setup>
import {onMounted, ref,defineProps,watch,toRefs} from 'vue'
import * as echarts from 'echarts'// 引入echarts

const props = defineProps({
  options:{
    type:Object,
    default:{},
    required:true
  },
  theme:{
    type:String,
    default:"",//dark為深色模式
    required:false
  }
})
const {options} = toRefs(props)
const container = ref(null)
const chart = ref(null)

//組件掛載后將echarts掛載在container上,並將給echarts設置傳入的options
onMounted(()=>{
  chart.value = echarts.init(container.value,props.options.theme)
  chart.value.setOption(props.options)
})

//監聽options發生變化時,重新給echarts設置傳入的options
watch(options,(newOptions)=>{
  chart.value.setOption(newOptions)
},
{deep:true}
)
</script>
<style scoped>
.container {
  width:100%;
  height: 100%;
}
</style>

二、使用Charts組件

在需要顯示echarts的頁面引入Charts.vue並傳入options參數,已官網實例為例

<template>
    <div class="chart">
     <Chart :options="options"/>
    </div>
</template>

<script setup>
import { reactive } from 'vue'
import Chart from '@/components/chart/Chart.vue'
const options = reactive({
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
})
</script>
<style scoped>
//注意 echarts 要求必須設置寬高才能正常繪制。
.chart {
  width: 400px;
  height: 400px;
}
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM