首页 > 解决方案 > 在 vuejs 中按 chartjs 中的提交时更新数据

问题描述

我正在创建一个在 vuejs 中显示数据的图表,我尝试labels再次更新但仍然无法正常工作。

ChartjsComponentLineChart.vue

<script>
import { Line } from 'vue-chartjs'

export default {
  extends: Line,
  props: {
    data: {
      type: Object,
      default: null,
    },
    options: {
      type: Object,
      default: null,
    },
    plugins: {
      type: Array,
      default: null,
    },
    styles: {
      type: Object,
      default: null,
    },
  },
  mounted() {
    this.renderChart(this.data, this.options, this.plugins, this.styles)
  },
}
</script>

report.vue中

 <b-card-body>
    <chartjs-component-line-chart
      :height="400"
      :data="data"
      :options="options"
      :plugins="plugins"
    />
  </b-card-body>

 <b-button
    variant="primary"
    class="btn-tour-finish"
    @click="submitData"
    >Submit
</b-button>



data() {
  return: {
     data: {
        labels: [],
        datasets: [
          {
            data: [70, 95, 100, 120, 257, 271, 300, 321, 383, 450],
            label: "Supper",
            borderColor: "#3e95cd",
          },
        ],
      },
      options: {
        title: {
          display: true,
          text: "Report",
        },
        responsive: true,
        maintainAspectRatio: false,
      },
  }
},
created() {
    this.data.labels = [1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025];
  },
methods: {
   submitData() {
     this.data.labels = [1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025, 2030];
  }
}

图表奏效了。但是当我点击提交时(submitData())不会labels更新。当我点击时,有没有办法更新“标签”。给我任何想法。谢谢

标签: vue.jschart.js

解决方案


Chart.js 本身不是响应式的,需要update在数据发生变化时自己调用该方法。这种开箱即用的非反应性行为正在被 vue-chartjs 接管。

要使其具有反应性,您需要根据文档将mixinreactiveProp添加到您的 lineChart 组件中。

import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],
  mounted () {
    // this.chartData is created in the mixin.
    // If you want to pass options please create a local options object
    this.renderChart(this.chartData, this.options)
  }
}

也可以自己实现watcher,按照文档自己调用chart.js的update方法

watch: {
  data () {
    this.$data._chart.update()
  }
}

推荐阅读