You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中mounted调用接口赋值data后DOM未重新渲染问题求助

Vue Mounted钩子中接口请求赋值后DOM不更新的原因分析

核心原因

  • 回调函数this指向丢失
    你将this.onSuccess直接作为参数传递给window.restEntity作为异步回调时,回调触发时的执行上下文已经不再是当前Vue实例,非严格模式下this会指向全局window对象。此时你赋值的this.displayedNotification是挂载在window上的普通变量,根本没有修改到Vue data中定义的响应式属性,自然不会触发响应式更新和DOM重渲染,即使使用this.$set也不会生效,因为this本身就指向错误。

提前用async await拿数据的写法正常工作的原因

你在Vue实例初始化前用async await拿到数据,再在mounted钩子中赋值时,this是正确指向当前Vue实例的,赋值操作是直接修改Vue的响应式属性,所以能正常触发DOM更新。

原写法修复方案

任选一种即可:

  1. 传递回调时绑定this指向
window.restEntity(
  'notifications',
  'read_notification_pref',
  {
    'entity': entityData, 
    'entity_id': entityId 
  },
  this.onSuccess.bind(this), // 绑定Vue实例作为this
  true
);
  1. 用箭头函数包裹回调,继承外层上下文的this
window.restEntity(
  'notifications',
  'read_notification_pref',
  {
    'entity': entityData, 
    'entity_id': entityId 
  },
  (resp) => this.onSuccess(resp), // 箭头函数自动继承外层this
  true
);
  1. 直接把onSuccess方法定义为箭头函数
methods: {
  // 其他方法省略
  onSuccess: (response) => {
    this.displayedNotification = response.data;
  }
}

内容的提问来源于stack exchange,提问作者NoobCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 01:54:06