我不能从父母那里更新孩子的数据。 Parent只发送初始数据,但是如果我按功能更新数据,那么我从后端获取它,没有任何改变。我甚至做了wacher,它工作然后数据更改(在控制台中写入调试字)但仍然没有发送更新的数据。我应该如何使用动态更改的数据来刷新父数据中的子项?
家长:
<el-date-picker
v-model="reportMonth"
type="month"
format="MMMM yyyy"
value-format="yyyy-MM-dd"
placeholder="Choose month"
@change="generateReport">
</el-date-picker>
<bar-chart :parent-data="sendData"></bar-chart>
data() {
return {
monthData: null,
sendData: {
lowRiskPreliminary: 0,
midRiskPreliminary: 0,
highRiskPreliminary: 0,
inadmissibleRiskPreliminary: 0,
notValidPreliminary: 0
}
watch: {
monthData: function() {
console.log('data changed!')
this.sendData = this.monthData
}
},
methods: {
generateReport() {
this.listLoading = true
getMonthlyReport(this.reportMonth).then(response => {
this.monthData = response.data }
儿童:
<template>
<div :class="className" :style="{height:height,width:width}"></div>
</template>
export default {
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '300px'
},
parentData: {
type: Object,
default: undefined
}
},
data() {
return {
chart: null,
lowRisk: [this.parentData.lowRiskPreliminary],
midRisk: [this.parentData.midRiskPreliminary],
highRisk: [this.parentData.highRiskPreliminary],
inhRish: [this.parentData.inadmissibleRiskPreliminary],
notVal: [this.parentData.notValidPreliminary]
}
},
mounted() {
this.initChart()
methods: {
initChart() {
this.chart = echarts.init(this.$el)
this.chart.setOption({
您将原始值undefined
作为parentData的默认值,并在更新父变量后将其更改为object。详情了解VueJS的反应性和警告:https://vuejs.org/v2/guide/reactivity.html
使用$nextTick
:
watch: {
monthData: function() {
this.$nextTick(function () {
this.sendData = this.monthData
})
}
}
或使用$ emit,从父级发出事件:
watch: {
monthData: function() {
this.$emit('monthDataUpdated', this.monthData);
}
}
在孩子:
events: {
'monthDataUpdated' : function(data){
this.$nextTick(function () {
this.parentData = data;
});
},
}
在子模板中打印sendData,如{{sendData}},您应该看到它发生了变化。