[英]How can I use props as option data of Echarts in a Vue 3 component?
所以我一直在嘗試使用 Echarts 制作折線圖。 我制作了這個LineChart.vue
並期望它從它的父組件中獲取 props,它們是數組,作為 Echarts 的選項數據。
但是作為數組代理的 props 似乎不能很好地工作。 控制台顯示它有正確的目標,但是這個代理不被Echarts識別,所以我的圖表上沒有數據。
為了讓它更奇怪,我偶然發現如果我保持終端打開,對代碼進行一些更改(這只是注釋和取消注釋相同的行),然后保存它(這可能會重新渲染這個組件),道具以某種方式起作用,折線圖實際上出現了! 但是如果我刷新頁面,數據又變空白了。
這是我的代碼:
<template>
<div id="chart"></div>
</template>
<script>
let chart;
export default {
data() {
return {
option: {
name: "demo",
xAxis: {
type: "category",
data: [],
},
yAxis: {
// type: "value",
},
series: [
{
data: [],
type: "line",
},
],
},
};
},
props: {
xAxisData: Array,
seriesData: Array,
},
methods: {
initChart() {
chart = this.$echarts.init(document.getElementById("chart"));
// these are the four lines that I commented and uncommented to make things wierd
this.option.xAxis.data = this.xAxisData;
this.option.series[0].data = this.seriesData;
console.log(this.option.xAxis.data);
console.log(this.option.series[0].data);
chart.setOption(this.option);
},
},
mounted() {
this.initChart();
},
watch: {
xAxisData: {
handler: function (newData) {
this.option.xAxis.data = newData;
},
deep: true,
},
seriesData: {
handler: function (newData) {
this.option.series[0].data = newData;
},
deep: true,
},
},
};
</script>
<style scoped>
#chart {
height: 250px;
width: 400px;
}
</style>
這是我對代碼進行一些小的更改之前和之后的代理是什么樣的我還嘗試使用Object.assign()
將此代理xAxisData
轉換為對象,但結果是空的! 我開始認為它可能與組件生命周期有關,但我不知道何時何地可以獲得功能代理。 有人可以告訴我實際發生了什么嗎?
剛剛想通了。 只是讓你知道,上面提供的信息是不夠的,我做了一個菜鳥舉動。
我的 vue 組件很好,是異步請求導致了這個問題。 我的 Echarts props 的數據是通過 Axios 請求重新獲取的,並且我的子組件(折線圖)在我獲得數據之前就已經渲染好了。 不知何故,數組的代理沒有數據,但他們得到了正確顯示的目標。 當我的子組件獲得正確的數據時,Echart 已經用過時的選項數據呈現,順便說一下,這些數據是空的。 這就是為什么重新渲染它可以向我們顯示數據。 它與代理無關,代理工作得很好。 是我更需要關注 aysnc 運動。 此外,我了解到 Echarts 顯然根本沒有反應性,所以我watch
了道具並更新了這樣的選項:
watch :{
xAxisData: {
handler: function (newData) {
this.option.xAxis.data = newData;
this.chart.clear();
this.chart.setOption(this.option);
},
deep: true,
},
}
有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.