javascript - 如何改变 VueJS Prop ?

标签 javascript chart.js vuejs2 vue-chartjs

您好,我无法理解如何在 vue js 中改变 prop 值。我正在使用 vue-chartjs 动态地重新呈现使用 chartjs 的图表。该行为有效,但当我启动 updateValues() 函数时收到控制台消息警告。

Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "myData"

如何正确地改变 prop?

// Parent Component
<bar-graph :myData="dataCollection" :height="250"></bar-graph>

data () {
  return {
    dataCollection: {
      labels: [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
      datasets: [
        {
          label: 'Sample Lables',
          backgroundColor: 'red',
          data: [5000, 5000, 5000, 5000, 5500, 5500, 10000, 5500, 5500]
        }
      ]
    }
  }
},
methods: {

  updateValues () {
    this.dataCollection = {
      labels: [5000, 5000, 5000, 5000, 5500, 5500, 10000, 5500, 5500],

      datasets: [
        {
          label: 'Sample Lables',
          backgroundColor: 'red',
          data: [5000, 5000, 5000, 5000, 5500, 5500, 10000, 5500, 5500]
        }
      ]
    }
  }
}
      
      
//Child component bar graph

import { Bar } from 'vue-chartjs'

export default Bar.extend({

  props: ['myData'],

  mounted () {
    this.renderChart(this.myData, {responsive: true, maintainAspectRatio: false})
  },
  watch: {
    myData: function () {
      console.log('destroy')
      this._chart.destroy()
      this.renderChart(this.myData, {responsive: true, maintainAspectRatio: false})
    }
  }
})

最佳答案

没有办法“正确地”改变 Prop ,因为它是组件的输入。

我建议将通过 prop 传递的数据导入组件的状态,然后相应地使用。通过使用此本地副本,您可以避免更改 prop 并收到该警告。

export default Bar.extend({

  props: ['myData'],

  data() {
    return {
      passedData: null
    }
  }

  mounted() {
    // Import data from prop into component's state
    this.passedData == this.myData;
    // Use as desired
    this.renderChart(this.myData, {
      responsive: true,
      maintainAspectRatio: false
    })
  },
  watch: {
    myData: function() {
      console.log('destroy')
      this._chart.destroy()
      this.renderChart(this.myData, {
        responsive: true,
        maintainAspectRatio: false
      })
    }
  }
})

关于javascript - 如何改变 VueJS Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43034098/

相关文章:

javascript - 使用 ChartJS 时多个数据集不起作用

javascript - 向 Chart.js 折线图添加标题

javascript - 仅执行 'onscroll'函数一次

javascript - @click 事件在 vue.js 应用程序中不起作用

javascript - Vue.js2 渲染空数组

javascript - 谁能帮我解释使用 selenium webdriver 进行图像验证的 javascript 代码?

javascript - 无法更新具有相同 id 的多个 div

javascript - 在 Vue 中使用带有动态属性的媒体查询

javascript - Component-changes.json 未找到 SAPUI5

javascript - ANTLR4 JavaScript Target非常慢