vue绑定失效的问题(操纵组件不更新)

问题背景

有一个父组件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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值