账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vue的生命周期中为什么beforeUpdate时的$el 和$data与updated时的数据一样?
    55
    0
    如题:vue的生命周期中beforeUpdate和updated这两个生命周期函数里数据好像是一样的?为什么beforeUpdate时的$el 和$data与updated时的一样? beforeUpdate: function() { console.group('beforeUpdate 更新前状态===============》') console.log('%c%s', 'color:red', 'el : ' + this.$el) console.log(this.$el) console.log('%c%s', 'color:red', 'data : ' + this.$data) console.log('%c%s', 'color:red', 'message: ' + this.message) console.log('el.innerHTML : ' + this.$el.innerHTML) }, updated: function() { console.group('updated 更新完成状态===============》') console.log('%c%s', 'color:red', 'el : ' + this.$el) console.log(this.$el) console.log('%c%s', 'color:red', 'data : ' + this.$data) console.log('%c%s', 'color:red', 'message: ' + this.message) console.log('el.innerHTML : ' + this.$el.innerHTML) },
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 傲う世ぁ猖狂 普通会员 1楼

      在Vue中,当使用beforeUpdate生命周期钩子函数更新组件的属性时,这个函数是绑定在$el和$data上。但是,在更新数据时,Vue会重新计算组件的状态,因此,当你使用updated钩子函数更新数据时,这个函数会与更新之前的数据不同。

      例如,假设你有一个组件,它有两个属性:$el和$data。在created钩子函数中,这两个属性的值都为undefined。

      javascript new Vue({ el: '#app', data: { value1: '', value2: '' }, created() { console.log('created:', this.value1, this.value2); }, beforeUpdate() { console.log('beforeUpdate:', this.value1, this.value2); this.value1 = 'new value'; this.value2 = 'new value'; }, updated() { console.log('updated:', this.value1, this.value2); console.log('updated data:', this.$el.dataset.value1, this.$el.dataset.value2); } });

      在上述代码中,当你使用updated钩子函数更新数据时,$el和$data的值都为新的值。但是,当你使用beforeUpdate钩子函数更新数据时,$el的值和$data的值都为undefined。这是因为Vue在更新数据时,会重新计算组件的状态,因此,$el和$data的值在更新数据时都会改变。

      如果你需要确保数据在更新前是不变的,你应该使用beforeUpdate钩子函数来更新数据。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部