问题背景
有一个父组件A:
<template>
<div class="app-container">
<B ref="child"></B>
</div>
</template>
<script>
export default {
created() {
api(id).then( res => {
this.$refs.child.data=res
this.$refs.child.data['period']=[res.startTime,res.endTime]
delete this.$refs.child.data['startTime']
delete this.$refs.child.data['endTime']
})
},
methods: {
}
}
</script>
子组件为:
<template>
<div class="app-container">
<el-form label-position="right" label-width="80px" :model="formData">
<el-card class="box-card" style="width:100%">
<el-row>
<el-col>
<el-form-item label="时间">
<el-date-picker
style="width:100%;"
value-format="yyyy-MM-dd"
v-model="formData.period"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期">
</el-date-picker>
</el-form-item>
</el-col>
</el-row>
</el-card>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
data: {
name: '',
period: ['','']
}
}
},
methods: {
}
}
</script>
问题描述
更改时间选择器后时间选择器不更新,但是实际的数据却更新了
问题原因
在父组件给子组件赋值时,首先将res赋值给child.data,但是res中并没有period属性,导致child.data中的period丢失,与组件的绑定断开,后续过程中再给child.data增加peroid属性后也无法建立绑定
受 ES5 的限制,Vue.js 不能检测到对象属性的添加或删除。因为 Vue.js 在初始化实例时将属性转为 getter/setter,所以属性必须在 data 对象上才能让 Vue.js 转换它,才能让它是响应的。 作者:再喝奶茶我就是狗 https://www.bilibili.com/read/cv13162287?from=search 出处:bilibili
解决方法
不要让子组件的已绑定属性丢失即可
res['period']=[res.startTime,res.endTime]
delete res['startTime']
delete res['endTime']
this.$refs.child.data=res