我在画布中显示了一个图表,我想从Vue 3观察程序中销毁并重新绘制它。观察程序工作,在更改时触发的函数一直工作到重新绘制步骤。当它到达重绘步骤时,我得到:
TypeError: Argument 1 ('element') to Window.getComputedStyle must be an instance of Element
图表对象加载为component
,并在最初安装时从method
进行渲染。我使用的是香草chart.js
(而不是vue-chartjs
(。
装载:
mounted() {
this.renderChart()
},
手表:
watch: {
'$store.state.weather': {
handler(newValue, oldValue) {
this.forecastChart.destroy()
this.animation = 0
this.renderChart() // works fine until this line
},
deep: true
}
}
方法:
methods: {
renderChart() {
let ctx = document.getElementById(this.id).getContext('2d');
this.forecastChart = new Chart(ctx, {
// source: https://stackoverflow.com/a/69047139/2827397
type: 'doughnut',
plugins: [{
beforeDraw: (chart) => {
const {ctx} = chart;
// etc.
类似的问题似乎有过时的解决方案,对我来说不起作用
理想情况下,我想让图表对Vuex存储状态值的变化做出反应,但破坏和重新绘制图表是可以接受的结果,这就是我的问题所在。
chart.js3.9.1
、vue3.0.0
、vuex4.0.2
编辑1:
尝试.update()
而不是.destroy()
图表对象也没有产生结果。
updateChart() {
this.forecastChart.data.datasets[0].needleValue = this.weather.airQuality - 0.5
this.forecastChart.update()
},
结果:
Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'item.fullSize = options.fullSize')
我不够聪明,无法解释原因,但下面的修订版解决了我面临的问题。上面,我用以下destroy()
命令引用了图表对象:
this.forecastChart.destroy()
虽然这个命令没有在控制台中显示任何错误,但它在这种情况下显然无法正常工作(同样重要的是,这里需要注意的是,这是在Vue 3中完成的(。
我将上面的行替换为:
let chartStatus = Chart.getChart(this.forecastChart)
chartStatus.destroy()
现在,原始图表被正确地销毁,新图表被绘制在它的位置。以下是相关代码:
watch: {
'$store.state.weather.airQuality': {
handler() {
this.updateChart()
},
deep: true
}
},
methods: {
updateChart() {
let chartStatus = Chart.getChart(this.forecastChart) // key change
chartStatus.destroy() // key change
this.animation = 0
this.renderChart()
},
renderChart() {
let ctx = document.getElementById(this.id).getContext('2d');
this.forecastChart = new Chart(ctx, {
type: 'doughnut',
plugins: [{
beforeDraw: (chart) => {
const {ctx} = chart;
// etc.