本文介绍如何将静态图表组件改造为支持动态传参的可复用 Vue 组件,通过 props 接收图表数据,利用响应式机制实现数据变更时图表自动更新,同时保持配置(如 title、尺寸)统一复用。
本文介绍如何将静态图表组件改造为支持动态传参的可复用 vue 组件,通过 `props` 接收图表数据,利用响应式机制实现数据变更时图表自动更新,同时保持配置(如 title、尺寸)统一复用。
要让图表真正“可复用”,关键在于解耦数据与组件逻辑——将固定数据移出组件定义,转为外部可配置的输入项。Vue 的 props 机制正是为此而生:它允许父组件向子组件安全、响应式地传递数据,并在数据变化时自动触发重渲染。
以下是改造后的可复用
// components/PieChart.vue
import { defineComponent, h } from 'vue';
import { GChart } from 'vue-google-charts';
export const type = 'PieChart';
export const options = {
title: 'My Daily Activities',
width: 450,
height: 250,
// 可在此统一配置所有图表共用的视觉/交互选项
};
export default defineComponent({
name: 'PieChart',
components: { GChart },
props: {
chartData: {
type: Array,
default: () => [
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
],
validator: (val) => Array.isArray(val) && val.length > 0
}
},
setup(props) {
return () => h(GChart, {
data: props.chartData,
options,
type
});
}
});
✅ 核心改进点说明:
- chartData 作为 prop 声明,类型为 Array,并提供清晰的默认值(兼容旧用法);
- 添加 validator 确保传入数据结构合法(首行为列标题,后续为数据行),提升组件健壮性;
- setup(props) 中直接将 props.chartData 绑定至 GChart 的 data 属性,借助 Vue 3 的响应式系统,任何对 chartData 的修改(如数组替换、ref 更新)都会实时反映在图表上。
在父组件中使用时,只需按需传入数据即可:
<!-- App.vue -->
<template><div class="chart-container">
<piechart :chart-data="currentData"></piechart><button>切换数据</button>
</div>
</template><script setup>
import { ref } from 'vue';
import PieChart from './components/PieChart.vue';
const currentData = ref([
['Product', 'Sales'],
['A', 42],
['B', 38],
['C', 29]
]);
const switchData = () => {
currentData.value = [
['Region', 'Revenue (M)'],
['North', 12.5],
['South', 9.8],
['East', 15.2],
['West', 11.1]
];
};
</script>
⚠️ 注意事项:
- vue-google-charts 的 GChart 组件依赖 data 的引用变化来触发重绘。因此请避免直接 .push() 或 .splice() 修改原数组(这不会触发响应式更新),推荐使用数组替换赋值(如 ref.value = newData);
- 若需深度监听嵌套数据变化(如动态增删行列),可配合 watch + chartWrapper.draw() 手动刷新,但绝大多数场景下 ref 替换已足够;
- options 和 type 保持导出常量形式,便于跨组件统一管理主题或全局配置。
通过这一模式,你可轻松衍生出
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











