您好,我无法理解如何在 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/