前提・実現したいこと
vue-chartjsを用いてデータを変更した際に描画されるようにしたいです。
inputの入力に基づいてラベルやデータを変更しそれが反映されてほしいです。
###現在
- 子コンポーネントにデータを渡し描画はできています。
- vue-chartjsでのリアクティブのサンプルを参考にデータをすべて上書きする場合はリアクティブが実現できています。
- inputなどでデータを変更するとリアクティブになりません。
- vue.jsではオブジェクトや配列の変更を検出できないせいかと思うのですが$set()を用いても解決できませんでした。
該当のソースコード
javascript
1//Bar.vue(子コンポーネント) 2//githubにあるサンプルのままです 3<script> 4import { Bar, mixins } from 'vue-chartjs' 5export default { 6 extends: Bar, 7 mixins: [mixins.reactiveProp], 8 props: ['chartData', 'options'], 9 10 mounted() { 11 this.renderChart(this.chartData, this.options) 12 }, 13 watch: { 14 chartData: function(val) { 15 this.renderChart(this.chartData, this.options) 16 }, 17 options: function(val) { 18 this.renderChart(this.chartData, this.options) 19 }, 20 }, 21} 22</script>
javascript
1//main.vue 親コンポーネント 2<template> 3 <div> 4 <Bar :chartData="datacollection" :options="options" :height="100" /> 5 </div> 6</template> 7 8<script> 9import Bar from '@/components/Bar' 10 11export default { 12 components: { 13 Bar, 14 }, 15 data() { 16 return { 17 datacollection: { 18 labels: ['赤', '青', '黄色', '緑', '紫', '橙'], 19 datasets: [ 20 { 21 label: '得票数', 22 data: [12, 19, 3, 5, 2, 3], 23 backgroundColor: [ 24 'rgba(255, 99, 132, 0.2)', 25 'rgba(54, 162, 235, 0.2)', 26 'rgba(255, 206, 86, 0.2)', 27 'rgba(75, 192, 192, 0.2)', 28 'rgba(153, 102, 255, 0.2)', 29 'rgba(255, 159, 64, 0.2)', 30 ], 31 borderColor: [ 32 'rgba(255,99,132,1)', 33 'rgba(54, 162, 235, 1)', 34 'rgba(255, 206, 86, 1)', 35 'rgba(75, 192, 192, 1)', 36 'rgba(153, 102, 255, 1)', 37 'rgba(255, 159, 64, 1)', 38 ], 39 borderWidth: 1, 40 }, 41 ], 42 }, 43 options: { 44 scales: { 45 yAxes: [ 46 { 47 ticks: { 48 beginAtZero: true, 49 }, 50 }, 51 ], 52 }, 53 }, 54 } 55 }, 56}
試したこと
html
1<button @click="$set(datacollection, 'labels', ['new赤', '青', '黄色', '緑', '紫', '橙'])">ボタン</button> 2<p>{{datacollection}}</p> 3 4//vue-panelを見るとデータは変更できているが 5//pタグの表示は切り替わらず、chartも変わらない 6//そもそもここでpタグの内容が変わらない理由がわからないです。 7
補足情報(FW/ツールのバージョンなど)
##追記
html
1<button @click="clicked">ボタン</button> 2<p>{{datacollection}}</p> 3 4clicked(){ 5 this.$set(datacollection, 'datasets', [ 6 { 7 label: '得票数', 8 data: [3, 3, 13, 15, 12, 13], 9 backgroundColor: [ 10 'rgba(0, 99, 132, 0.2)', 11 'rgba(54, 162, 235, 0.2)', 12 'rgba(0, 206, 86, 0.2)', 13 'rgba(75, 192, 192, 0.2)', 14 'rgba(153, 102, 0, 0.2)', 15 'rgba(0, 159, 64, 0.2)', 16 ], 17 borderColor: [ 18 'rgba(255,99,132,1)', 19 'rgba(54, 162, 235, 1)', 20 'rgba(255, 206, 86, 1)', 21 'rgba(75, 192, 192, 1)', 22 'rgba(153, 102, 255, 1)', 23 'rgba(255, 159, 64, 1)', 24 ], 25 borderWidth: 1, 26 }, 27} 28//としたところ、これはpタグの内容が更新されました 29//chartは相変わらず変わりません 30
##追記2
ドキュメントより
On data change, it will either call update() if only the data inside the datasets has changed or renderChart() if new datasets were added.
とあるのでdatasetsの変更にも対応しているのではと思っています
あなたの回答
tips
プレビュー