vue3.0 通过ref 动态绑定与获取 dom
html写法
<li
v-for="item in Overview.config"
:key="item.value"
>
<BarChart
:ref="item.value+'ChartRef'"
style="height: 120px"
:ids="item.value"
/>
</li>
数据
Overview = {
data: [],
config: [{
value: 'cellNumber',
title: '小区数',
color: ['#7FB9ED', '#1E88E5'],
unit: '个'
},
{
value: 'energySavingCell',
title: '节能小区数',
color: ['#7FB9ED', '#1E88E5'],
unit: '个'
},
{
value: 'saveEnergy',
title: '节省能耗',
color: ['#E35500', '#FF8A00'],
unit: 'kW·h'
}]
}
定义ref并赋值
const cellNumberChartRef = ref(null)
const energySavingCellChartRef = ref(null)
const saveEnergyChartRef = ref(null)
调用组件方法
cellNumberChartRef.value[0].drawCharts({
data: Overview.data,
config: Overview.config.find(item => item.value === 'cellNumber')
})
energySavingCellChartRef.value[0].drawCharts({
data: Overview.data,
config: Overview.config.find(item => item.value === 'energySavingCell')
})
saveEnergyChartRef.value[0].drawCharts({
data: Overview.data,
config: Overview.config.find(item => item.value === 'saveEnergy')
})
以上写法在本地运行时可以正常展示,但打包上线后要报错,表示获取不到ref,即xxxChartRef.value[0] is undefined
解决办法:通过 动态绑定 attribute属性及ref绑定函数 实现动态ref
html写法
<li
v-for="item in Overview.config"
:key="item.value"
>
<BarChart
:ref="setChartRef"
style="height: 120px"
:ids="item.value"
:ref="setChartRef"
/>
</li>
定义ref并赋值
const chartRefs = {}
const setChartRef = el => {
if (el && el.$attrs.name) {
chartRefs[el.$attrs.name] = el
}
}
调用组件方法
for (const key in chartRefs) {
Overview.totalData[key] && chartRefs[key].drawCharts({
data: Overview.data,
config: Overview.config.find(item => item.value === key)
})
}