Vue2 超详细:手把手教你封装折线图组件
以下是一个简单的折线图组件的封装示例: ```vue <template> <div class="line-chart"> <canvas ref="chartCanvas" width="400" height="200"></canvas> </div> </template> <script> import Chart from 'chart.js'; export default { name: 'LineChart', props: { data: { type: Array, required: true } }, mounted() { this.renderChart(); }, methods: { renderChart() { const ctx = this.$refs.chartCanvas.getContext('2d'); new Chart(ctx, { type: 'line', data: { labels: this.data.map(item => item.label), datasets: [ { label: '折线图', data: this.data.map(item => item.value) } ] }, options: { responsive: true, maintainAspectRatio: false } }); } } }; </script> <style scoped> .line-chart { width: 400px; height: 200px; } </style> ``` 在使用组件时,可以通过传递一个数组给 `data` 属性来设置折线图的数据,数组中每个对象包含 `label` 和 `value` 属性,分别表示折线图的标签和值。例如: ```vue <template> <div> <line-chart :data="chartData" /> </div> </template> <script> import LineChart from './LineChart.vue'; export default { components: { LineChart }, data() { return { chartData: [ { label: '1月', value: 100 }, { label: '2月', value: 150 }, { label: '3月', value: 200 }, { label: '4月', value: 120 }, { label: '5月', value: 180 } ] }; } }; </script> ``` 通过传递不同的 `chartData` 数组,可以实现不同的折线图效果。 ######[AI写代码神器 | 1080点数解答 | 2024-06-21 14:05:34]
- 速览!Vue 父组件与子组件生命周期钩子执行顺序全解析(阿里通义 | 226点数解答 | 2023-11-09 01:49:24)266
- 缜密逻辑,全新无名杀“风餐”技能代码精心打造与深度解析 (字节豆包 | 469点数解答 | 2025-04-05 11:37:06)240
- Vue2 巧用递归组件,实现多级表头组件封装(GPT | 1422点数解答 | 2024-05-28 15:32:14)296
- Vue2 超详细:手把手教你封装折线图组件(GPT | 1080点数解答 | 2024-06-21 14:05:34)283
- 深度剖析 Vue 2 插槽:从基础使用到高级玩法(字节豆包 | 165点数解答 | 2024-11-29 11:25:06)214