共计 2362 个字符,预计需要花费 6 分钟才能阅读完成。
目前市面上许多项目都会接触到可视化大屏的开发, 用得最多的三方组件库 Echarts, 在进行封装后复用许多同学会发现页面渲染异常问题, 只会渲染第一次复用的内容. 究其原因在于我们通过 Id 获取了页面节点进行渲染造成了 id 的重复. 网上也有许多的解决方案. 在此, 给大家分享一个自己测试后的可行的实施方案. 我们可以通过 uuid 生成不同的 id 向子组件传值指定唯一性, 也可以通过随机数的方式. 具体的操作我们接着往下看.
首先我们需要将需要复用的组件进行简单的封装. commonEcharts.vue(子组件)
然后在需要使用的组件中父组件 () 引入对应的组件.expControl.vue
import charts from '../../../components/copycompnents/commonEcharts.vue'
接下来解决 id 复用的问题, 新建一个 js 或 ts 文件, 对方法进行封装并导出引入.
新建 createID.js 文件
export function createId(){return 'id' +Math.random()
}
引入 js 文件
import {createId} from '../../../api/createId'
在父组件中传入配置项 option, 这儿一折线图为例
let lineTwo = reactive({color: ['#0298DB', '#F59A23'],
title: {
text: '出院人次数',
left: 80,
top: 20,
textStyle: {
fontWeight: 400,
fontFamily: 'Arial Normal',
fontStyle: 'normal',
fontSize: 20,
color: '#555555'
}
},
grid: {
top: 70,
bottom: 40,
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
crossStyle: {color: '#999'}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['1 月', '2 月', '3 月', '4 月', '5 月', '6 月', '7 月', '8 月', '9 月', '10 月', '11 月', '12 月']
},
yAxis: {
type: 'value',
show: true,
min: 0,
max: 5000,
iterval: 1000,
axisLine: {show: true},
axisLabel: {formatter: function (value, index) {return value>= 1000 ? parseInt(value / 1000) + '千' : value;
}
},
axisPointer: {type: 'shadow'}
},
legend: {// itemStyle: {}, // 继承系列中属性值的颜色
right: 80,
top: 15,
itemGap: 20,
itemWidth: 9,
itemHeight: 10,
data: [{ icon: 'rect', name: '今年'},
{icon: 'rect', name: '去年'}
],
textStyle: {
fontWeight: 400,
fontFamily: 'Arial Normal',
fontStyle: 'normal',
fontSize: 20,
color: '#555555',
}
},
series: [
{
name: '今年',
symbol: 'none',
data: [1500, 2300, 2240, 2180, 1350, 1470, 2600, 1110, 1230, 1450, 1680, 2360],
type: 'line'
},
{
name: '去年',
symbol: 'none',
data: [1000, 1300, 2504, 3080, 1050, 1740, 2200, 2120, 1230, 1550, 1460, 1530],
type: 'line'
}
]
})
在父组件中传值
子组件通过 difineprops 接收父组件传过来的值
let {id, option} = defineProps({
option: Object,
id: String
})
效果图:
个人经验. 分享一下. 共同学习, 欢迎指正.
原文地址: 关于 Echarts 图表复用解决 id 唯一性
正文完