專案場景:
資料可視化開發,采用的技術堆疊是vue3+echarts+router,
問題描述:
在vue2中,才開始開發資料可視化大屏,都是用echarts,之后改用為vue-echarts組件,但是到了vue3之后,組件會有一些小問題,所以準備自己封裝一套簡易的vue-echarts組件,其他的功能之后再迭代上去,足夠專案使用即可,
代碼封裝:
<template>
<div class="echarts" :id="id"></div>
</template>
這里的echarts組件的id應該每個組件不同,因此id值為動態設定的,
<script>
import { onMounted } from 'vue'
import { uuid } from '../../utils/index'
import Echarts from 'echarts'
export default {
name: 'TwokeVueEcharts',
props: {
options: {
type: Object,
default: () => ({})
}
},
setup (ctx) {
const id = `vue-echarts-${uuid()}`
let chart = null
const initEcharts = () => {
if (!chart) {
const dom = document.getElementById(id)
chart = Echarts.init(dom)
}else {
return
}
if(!ctx.options) return
chart.setOption(ctx.options)
}
onMounted( () => {
initEcharts()
})
return {
id
}
}
}
</script>
這里可以看到我引入了uuid的工具類,是為了生成唯一的id值,這里也可用時間戳搭配前綴來實作,回傳id值以供視圖渲染,引入的echarts為echarts官方組件
<style lang="scss" scoped>
.echarts {
width: 100%;
height: 100%;
}
</style>
這里是讓echarts組件可以根據外面的容器大小,鋪滿展示,
組件使用
兩種方式:
全域安裝
main.js中
import TwokeVueEcharts from './TwokeVueEcharts.vue'
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).component("vue-echarts",TwokeVueEcharts).mount("#app")
組件中引入
<script>
import TwokeVueEcharts from './TwokeVueEcharts.vue'
export default {
components: {
TwokeVueEcharts
}
}
</script>
<template>
<div style="width:300px;height:300px">
<twoke-vue-echarts :options="options"></twoke-vue-echarts>
</div>
</template>
<script>
import TwokeVueEcharts from './TwokeVueEcharts.vue'
export default {
components: { TwokeVueEcharts },
setup () {
return {
options: {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 10,
data: ['事件一 名稱', '事件二 名稱', '事件三 名稱', '事件四 名稱'],
padding: [250, 6, 7, 8]
},
grid: {
top: 0,
left: 0,
right: 0,
bottom: 0
},
series: [
{
name: '訪問來源',
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '30',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{ value: 335, name: '事件一 名稱' },
{ value: 310, name: '事件二 名稱' },
{ value: 234, name: '事件三 名稱' },
{ value: 135, name: '事件四 名稱' }
]
}
]
}
}
}
}
</script>

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/239187.html
標籤:其他
