【发布时间】:2021-11-11 11:50:28
【问题描述】:
所以我一直在尝试使用 Echarts 制作折线图。我做了这个LineChart.vue 并期望它从它的父组件中获取道具,即数组,作为 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>
这里是what is the proxy like before and after I made some minor changes to the code
我还尝试使用Object.assign() 将这个代理xAxisData 变成一个对象,但结果是空的!我开始认为它可能与组件生命周期有关,但我不知道何时何地可以获得功能代理。谁能告诉我到底发生了什么?
仅供参考,这里是value of props in console 和value of props in vue devtool。
【问题讨论】:
-
您看到的代理是 vue 添加的,用于跟踪数据更改以实现反应性目的。大多数代码将像普通对象或数组一样透明地访问/使用代理,并且看不到任何区别。 vue 3 文档中对此进行了解释。 (是的,vue 2 也一样)v3.vuejs.org/guide/reactivity.html#how-vue-tracks-these-changes
-
发布
xAxisData和seriesData的值。 -
@bassxzero 感谢大家的关注,而且有趣的是,根据 vue devtools 的说法,
xAxisData和seriesData都是Array[24],它的内容正是我想要的。但显然 Echarts 和控制台日志不这么认为。 -
The proxied object is invisible to the user, but under the hood it enables Vue to perform dependency-tracking and change-notification when properties are accessed or modified. One caveat is that console logging will format proxied objects differently, so you may want to install vue-devtools (opens new window)for a more inspection-friendly interface.我发给你的链接特别提到为什么console.log显示Proxy -
是的,谢谢@bassxzero,但真正困扰我的是为什么我的图表没有显示我期望的数据,至少在我手动重新渲染组件之前没有。 TBH,我不介意道具是数组还是代理,只要它有效。而且我确信代理可以工作,但我的没有,我想知道我做错了什么。
标签: javascript vue.js echarts