index.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { defineComponent, onMounted, ref, watch, onBeforeUnmount } from 'vue'
  2. import '@/common/map/fujian'
  3. import theme from '@/common/map/theme' // 引入默认主题
  4. import * as echarts from 'echarts'
  5. // 定义类型
  6. const PropsType = {
  7. id: String,
  8. className: {
  9. type: String,
  10. default: 'chart'
  11. },
  12. width: {
  13. type: String,
  14. require: true
  15. },
  16. height: {
  17. type: String,
  18. require: true
  19. },
  20. options: {
  21. type: Object,
  22. default: () => ({}),
  23. require: true
  24. }
  25. } as const
  26. export default defineComponent({
  27. name: 'Echarts',
  28. props: PropsType,
  29. setup(props) {
  30. const chartRef = ref<HTMLElement>()
  31. const chart = ref<any>()
  32. // 初始化echart
  33. const initChart = () => {
  34. chart.value.setOption(props.options, true)
  35. }
  36. // 生命周期
  37. onMounted(() => {
  38. // 定义实例
  39. echarts.registerTheme('myTheme', theme) // 覆盖默认主题
  40. chart.value = echarts.init(chartRef.value, 'myTheme')
  41. initChart()
  42. })
  43. onBeforeUnmount(() => {
  44. chart.value.dispose()
  45. chart.value = null
  46. })
  47. // 监听改变
  48. watch(
  49. () => props.options,
  50. val => {
  51. val && initChart()
  52. },
  53. {
  54. deep: true
  55. }
  56. )
  57. return () => {
  58. const { id, className, height, width } = props
  59. return <div
  60. ref={chartRef}
  61. id={id as string}
  62. class={className as string}
  63. style={{
  64. 'height': height as string,
  65. 'width': width as string
  66. }}
  67. />
  68. }
  69. }
  70. })