繁体   English   中英

Vue ChartJS折线图不显示

[英]Vue ChartJS Line Chart not displaying

我正在使用带有 vue-chartjs 包装器的 chartjs,并尝试使用从我的 api 获取的数据创建折线图。 数据按预期打印到控制台,我没有在控制台中收到错误。 结果折线图根本不显示在浏览器中。 然而,在注入canvas标签的地方有大量空白。 我可以很好地创建一个圆环图,而不是这个折线图。 非常感谢您的帮助! 我正在使用https://vue-chartjs.org/examples/中的图表示例中的代码作为LineChart组件

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选项似乎被定义为 object 但应该是一个数组。

 data: {
      labels: dates,
      datasets: { // <--- should be an array.
        label: 'Ratings by date',
        data: ratings,
        backgroundColor: '#f87979'
      }
    },

它应该是:

 data: {
      labels: dates,
      datasets: [{
        label: 'Ratings by date',
        data: ratings,
        backgroundColor: '#f87979'
      }]
    },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM