如果要在 Vue Composition API 來使用 Chart.js ,同時在更換資料時,圖表也要更新,要怎麼做?讓我來筆記一下詳細作法。
設定 <template> 的 <canvas>
Chart.js 是使用 <canvas>來繪製圖表,所以必須設置一個 <canvas> 來讓 Chart.js 畫圖,我們在 <canvas> 標籤中加上ref=”chartElement”,等等使用 Vue3 Composition API 可以用來指定繪圖的位置。
<canvas ref="chartElement"></canvas>完整的 <template>
<template>
<main>
<button @click="switchData" style="margin-bottom: 20px;">切換數據</button>
<div class="canvas-box">
<!-- 生成圖表的 canvas -->
<canvas ref="chartElement"></canvas>
</div>
</main>
</template>
引入
在<script> 一開始就引入要用到的 Chart.js 與 Vue 的方法與鉤子。
import { ref, shallowRef, computed, watch, nextTick, onMounted } from 'vue'
import Chart from 'chart.js/auto'設置變數
- dataArray:用來存放要跑線圖的資料。
- chartElement = ref(null):用來取得要拿來畫圖表的 canvas 元素。
- dataChart:儲存 new Chart 方法生成的圖表。
// 要跑圖表折線的資料陣列
const dataArray = ref([10, 20, 15, 25])
// 取得要放圖表的 canvas 元素
const chartElement = ref(null)
// 儲存 new Chart 生成的圖表
const dataChart = shallowRef(null)初始化
建立一個初始化函式,用 Chart.js 的 new Chart 方法來生成圖表,這時我們要把它存在 dataChart 這個 ref。
dataChart.value = new Chart(chartElement.value.getContext('2d'), {參數物件})const init = (ws) => {
dataChart.value = new Chart(chartElement.value.getContext('2d'), {
type: 'line',
data: {
labels: ['鋼鐵人', '蜘蛛人', '美國隊長', '雷神'],
datasets: [
{
label: '出勤次數',
data: ws.value,
backgroundColor: '#B7EDA1',
borderColor: '#1BAD4F',
borderWidth: 1,
fill: true
}
]
},
options: {
responsive: true,
maintainAspectRatio: false
}
})
}onMounted
onMounted(() => {
nextTick(() => {
init(dataArray);
})
})更新圖表
這次比較不一樣的地方在於,我們在希望可以切換數據後,更新圖表。
- 切換數據的函式。
- watch 監聽數據變化,更新圖表
切換數據的函式:
// 隨機產生數字
function getRandomInt() {
return Math.floor(Math.random() * (50 - 5 + 1)) + 5
}
const switchData = () => {
dataArray.value = [
getRandomInt(),
getRandomInt(),
getRandomInt(),
getRandomInt(),
];
}watch 監聽:
watch(dataArray, (newDataArray) => {
const ws = [...newDataArray]
dataChart.value.data.datasets[0].data = ws
dataChart.value.update()
}, { deep: true })