Vue ChartJS折线图无法显示问题求助
Vue-ChartJS折线图不显示(数据正常但画布空白)
我用vue-chartjs封装ChartJS,通过API获取数据创建折线图时,数据能正常打印到控制台且无报错,但折线图在浏览器中完全不显示,仅canvas标签位置有大片空白区域。环形图可正常创建,仅折线图存在问题。相关代码如下:
相关代码
IndexView.vue
<script setup> import axios from 'axios' import { onMounted, reactive } from 'vue' import LineChart from '@/components/LineChart.vue' const data = reactive({ user: null, totals: null, checkins: null }) const state = reactive({ loading: true }) const charts = reactive({ doughnutConfig: null, lineConfig: null }) onMounted(async () => { // load data from store and api data.user = await userStore.fetchUser() const user_resp = await axios.get(...) data.totals = user_resp.data.totals data.checkins = user_resp.data.check_ins state.loading = false // create line chart var dates = [] var ratings = [] var length = data.checkins.length < 10 ? data.checkins.length : 10 for (var i = 0; i < length; i++) { dates.push(data.checkins[i].date) ratings.push(data.checkins[i].rating) } console.log(dates) // [ "2022-09-04T00:00:00", "2022-09-04T00:00:00", "2022-09-04T00:00:00", "2022-09-04T00:00:00", "2022-09-05T00:00:00" ] console.log(ratings) // [ 5, 5, 3, 2, 4 ] charts.lineConfig = { data: { labels: dates, datasets: { label: 'Ratings by date', data: ratings, backgroundColor: '#f87979' } }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } } } }) </script> <template> <LineChart v-if="charts.lineConfig" :chart-options="charts.lineConfig.options" :chart-data="charts.lineConfig.data" :width="400" :height="300" /> </template>
LineChart.vue
<script setup> import { defineProps } from 'vue' import { Line } from 'vue-chartjs' import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale } from 'chart.js' ChartJS.register( Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale ) const props = defineProps({ chartData: { type: Object, required: true }, chartOptions: { type: Object, required: true }, chartId: { type: String, default: 'line-chart' }, width: { type: Number, required: true }, height: { type: Number, required: true } }) </script> <template> <Line :chart-id="props.chartId" :chart-data="props.chartData" :chart-options="props.chartOptions" :width="props.width" :height="props.height" /> </template>
解决方案
问题出在折线图的datasets格式错误:ChartJS要求datasets是一个数组,而非单个对象。你的代码里把datasets写成了单个对象,导致ChartJS无法识别数据系列,因此无法渲染折线图。
修改IndexView.vue中charts.lineConfig.data的datasets部分,将其改为数组格式:
charts.lineConfig = { data: { labels: dates, // 将datasets从对象改为数组,包裹单个数据集对象 datasets: [ { label: 'Ratings by date', data: ratings, backgroundColor: '#f87979', // 添加borderColor确保折线可见(backgroundColor是填充色,折线需要边框色) borderColor: '#f87979', fill: false // 不需要填充区域时设置为false,符合常规折线图效果 } ] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } } }
修改后重新运行,折线图即可正常渲染。
内容的提问来源于stack exchange,提问作者Fouroh3
相关产品推荐
相关产品推荐

