ChartJS 带有vue的Charts.js在获取数据后不绘制图表

zxlwwiss  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(229)

这是json响应的样子[[61,57,34],[1,1,3]]我想用第一个数组来存放标签,第二个数组来存放数据。
如果我在app中手动设置labels and data,它仍然有效。
例如labels: ["q", "w", "e"]data: [1, 5, 10]

  1. Vue.component('chart', {
  2. props: ['labels', 'data', 'type'],
  3. template: `
  4. <canvas style="width: 512px; height: 256px"></canvas>
  5. `,
  6. mounted: function () {
  7. new Chart(this.$el, {
  8. type: this.type,
  9. data: {
  10. labels: this.labels,
  11. datasets: [{
  12. label: '# of Votes',
  13. data: this.data,
  14. borderWidth: 1
  15. }]
  16. },
  17. options: {
  18. scales: {
  19. yAxes: [{
  20. ticks: {
  21. beginAtZero:true
  22. }
  23. }]
  24. }
  25. }
  26. })
  27. }
  28. });
  29. new Vue({
  30. el: '#app',
  31. data: {
  32. message: "test",
  33. labels: [],
  34. data: []
  35. },
  36. methods: {
  37. fetchData: function() {
  38. this.$http.get('/admin/fetch_data').then(res => {
  39. this.labels = res.body[0];
  40. this.data = res.body[1];
  41. })
  42. }
  43. },
  44. beforeMount() {
  45. this.fetchData()
  46. }
  47. });

页面上的组件

  1. <div id="app">
  2. {{message}}
  3. <chart :labels="labels" :data="data" type="bar"></chart>
  4. </div>

数据似乎已加载,但页面上没有条形图。

jaxagkaj

jaxagkaj1#

问题是当你正在执行一个异步任务来获取你的数据时,你的数据还没有被获取。到那时,组件的挂载钩子会被空的props调用,因为你作为props传递的数据还没有被加载。
所以这样做:

  1. Vue.component('chart', {
  2. props: ['labels', 'data', 'type' 'loaded'],
  3. template: `
  4. <canvas style="width: 512px; height: 256px"></canvas>
  5. `,
  6. watch:{
  7. loaded(isLoaded){
  8. if(isLoaded){
  9. this.drawChart();
  10. }
  11. }
  12. },
  13. methods:{
  14. drawChart: function () {
  15. new Chart(this.$el, {
  16. type: this.type,
  17. data: {
  18. labels: this.labels,
  19. datasets: [{
  20. label: '# of Votes',
  21. data: this.data,
  22. borderWidth: 1
  23. }]
  24. },
  25. options: {
  26. scales: {
  27. yAxes: [{
  28. ticks: {
  29. beginAtZero:true
  30. }
  31. }]
  32. }
  33. }
  34. })
  35. }
  36. }
  37. });
  38. new Vue({
  39. el: '#app',
  40. data: {
  41. message: "test",
  42. labels: [],
  43. data: [],
  44. loaded: false
  45. },
  46. methods: {
  47. fetchData: function() {
  48. this.$http.get('/admin/fetch_data').then(res => {
  49. this.labels = res.body[0];
  50. this.data = res.body[1];
  51. this.loaded = true;
  52. })
  53. }
  54. },
  55. created() {
  56. this.fetchData()
  57. }
  58. });

html格式

  1. <div id="app">
  2. {{message}}
  3. <chart :labels="labels" :data="data" :loaded="loaded" type="bar"></chart>
  4. </div>
  • 在root vue示例中添加一个设置为false属性loaded,并将其作为prop传递
  • 在由ths.$http.get()请求返回的promise的成功回调中,将loaded更改为true
  • 在您的chart组件中设置一个监视器来监视这个loaded属性
  • loaded属性changes to为真时调用drawChart方法'
展开查看全部

相关问题