vue.js - 如何在 Vuejs 上进行图表专家更新
问题描述
首先祝大家新年快乐。
我想打电话update
给chartist-js
。
main.js
import Chartist from "chartist";
Vue.prototype.$Chartist = Chartist;
Component.vue
<chart-card
:chart-data="performanceUser.data"
:chart-options="performanceUser.options"
chart-type="Line"
data-background-color="green">
</chart-card>
Component.vue -> methods
getStatsUser(){
UsersAPI.getUserPerformance(this.users.filters.user.active).then(r => {
this.performanceUser.data.labels = r.data.labels;
this.performanceUser.data.series = r.data.series;
this.$Chartist.update();
});
}
解决方案
您需要做几件事。首先,您不需要使用Chartist实例修补 Vue 原型对象。只需在需要的地方导入Chartist
包即可。当您需要单例或有状态构造时,需要进行原型修补。
其次,我假设您所有的图表呈现逻辑都将在您的chart-card
组件中。它大致看起来像:
<template>
<!-- Use vue.js ref to get DOM Node reference -->
<div class="chart-container" ref="chartNode"></div>
</template>
<script>
import Chartist from 'chartist';
export default {
// data is an object containing Chart X and Y axes data
// Options is your Chartist chart customization options
props: ['data', 'options'],
// Use of mounted is important.
// Otherwise $refs will not work
mounted() {
if (this.data && this.options) {
// Reference to DOM Node where you will render chart using Chartist
const divNode = this.$refs.chartNode;
// Example of drawing Line chart
this.chartInstance = new Chartist.Line(divNode, this.data, this.options);
}
},
// IMPORTANT: Vue.js is Reactive framework.
// Hence watch for prop changes here
watch: {
data(newData, oldDate) {
this.chartInstance.update(newData, this.options);
},
options(newOpts) {
this.chartInstance.update(this.data, newOpts);
}
}
}
</script>
最后,在您的调用组件中,您将拥有:
getStatsUser() {
UsersAPI.getUserPerformance(this.users.filters.user.active).then(r => {
// Since component is watching props,
// changes to `this.performanceUser.data`
// should automatically update component
this.performanceUser.data = {
labels: r.data.labels,
series: r.data.series
};
});
}
我希望这能让您了解如何为 Chartist 图表构建 Vue 包装器。
推荐阅读
- visual-studio-code - VS 代码未解决的导入
- macos - 无法使用 Apple M1 芯片将 Flutter 安装到 macOS Big Sur
- python - Show more using Selenium requires sleep
- node.js - node-v 没有显示我系统上安装的当前节点版本
- python - 如何检查重复行中的目标变量是否不同
- flutter - 当我弹回前一个屏幕时,FadeInImage 小部件“淡入”
- python - 如何按该元素的大小重复列表中的元素的次数
- domain-driven-design - 管理聚合边界 (DDD)
- c++ - ld:架构 arm64 的 24 个重复符号?
- macos - 有没有办法使用 SwiftUI 检索 macOS 中文件和文件夹的图标图像?