ehcarts在vue3中只能加computed才能通过接口去刷新数据嘛?
怎么在设置默认数据后,不通过v-if
判断chartList
有没有数据。或者不设置computed
,在获取接口值后渲染出图例?
父组件
// 饼图组件<BarChart
:chartId="'BarChartId1'"
:xAxisData="chartList.xAxisData"
:seriesData="chartList.seriesData"
></BarChart>
// 饼图数据
chartList: {
xAxisData: ['xxx'],
seriesData: [
{
name: 'xxx'
value: 111,
}
],
},
// 父组件获取饼图接口数据
proxy.$request
.get(`/overview/getData`, {
params,
})
.then((res) => {
console.log(res.data.pieChartData)
state.chartList = res.data.pieChartData
})
饼图不加 computed
不能刷新数据。
在接口获取到数据以后,watch
确实在最后打印出了新数据,但是图例只是刷了一下,数据却没有更新成接口的数据,还是初始设置的数据
let setOptions = { // option数据
}
// 创建图表
const initChart = () => {
echarts.dispose(document.getElementById(props.chartId))
state.myChart = echarts.init(document.getElementById(props.chartId))
window.addEventListener('resize', () => {
state.myChart.resize()
})
state.myChart.setOption(setOptions, true)
}
onMounted(() => {
nextTick(() => {
console.log(props.seriesData)
initChart()
watch(
[() => props.xAxisData, () => props.seriesData],
(newVal) => {
console.log(newVal)
state.myChart.clear()
initChart()
return newVal
},
{
deep: true,
// immediate: true,
}
)
})
})
onUnmounted(() => {
echarts.dispose()
state.myChart = null
})
回答:
父组件:
<template> <BarChart :chartId="'BarChartId1'" :xAxisData="chartList.xAxisData" :seriesData="chartList.seriesData" />
</template>
<script>
import { ref } from 'vue'
import BarChart from './BarChart.vue'
export default {
components: {
BarChart
},
setup() {
const chartList = ref({
xAxisData: ['xxx'],
seriesData: [
{
name: 'xxx',
value: 111
}
]
})
// 模拟异步请求
setTimeout(() => {
chartList.value = {
xAxisData: ['yyy'],
seriesData: [
{
name: 'yyy',
value: 222
}
]
}
}, 3000)
return {
chartList
}
}
}
</script>
子组件:
<template> <div :id="chartId" style="width: 600px; height: 400px;"></div>
</template>
<script>
import { onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
export default {
props: {
chartId: String,
xAxisData: Array,
seriesData: Array
},
setup(props) {
let myChart = null
const setOptions = () => {
return {
// 根据 props.xAxisData 和 props.seriesData 更新 option 数据
}
}
const initChart = () => {
echarts.dispose(document.getElementById(props.chartId))
myChart = echarts.init(document.getElementById(props.chartId))
window.addEventListener('resize', () => {
myChart.resize()
})
myChart.setOption(setOptions(), true)
}
onMounted(() => {
nextTick(() => {
initChart()
watch(
[() => props.xAxisData, () => props.seriesData],
() => {
myChart.clear()
initChart()
},
{
deep: true
}
)
})
})
onUnmounted(() => {
echarts.dispose()
myChart = null
})
return {}
}
}
</script>
以上是 ehcarts在vue3中只能加computed才能通过接口去刷新数据嘛? 的全部内容, 来源链接: utcz.com/p/934266.html