【问题标题】:DOM is not re-rendering on change of data in vueDOM 不会在 vue 中的数据更改时重新渲染
【发布时间】:2021-07-29 04:06:57
【问题描述】:

我正在从 Mounted Lifecycle Hook 调用一个方法,该方法实际上是调用一个返回响应的后端服务。但是当我将该响应分配给数据时,它不会重新渲染 DOM。我认为它没有得到被动更新。以下是我的代码:

vmObj = new Vue({
  el: el[0],
  template: notificationTemplate,
  mixins: [translation_mixin],
  components: {
    notification_row
  },

  data: function() {
    return {
      'displayedNotification': []
    };
  },
  methods: {

    getNotificationData() {
          window.restEntity(
                        'notifications',
                        'read_notification_pref',
                        {
                            'entity': entityData, 
                            'entity_id': entityId 
                        },
                        this.onSuccess,
                        true
                    );
      //BackEnd Service which when returns a response we call "onSuccess(resp)"
    },

    onSuccess(response) {
      this.displayedNotification = response.data; //I also used this.$set but nothing happening
    }
  },

  mounted() {
    this.getNotificationData();
  }
});

更新:

所以真的不是一个答案,但我必须在渲染 Vue 之前调用该服务(之前: vmObj = new Vue({.....) 例如,使用asyncawait,并将响应保存在一个变量中,然后在Mounted Hook中分配数据,现在它可以工作了。

【问题讨论】:

  • 请在getNotificationData或密码箱中分享代码。见minimal reproducible example
  • 致电onSuccess 后,您是否在调试器或Vue devtools 中验证displayedNotification 具有您期望的正确数据?
  • @FrankPl 是的,数据已正确分配给 displayNotification 。但是有些 DOM 是如何不重新渲染的。我注意到一件奇怪的事情,如果我将调试器放在mounted() { this.getNotificationData(); ----->>>>} 在这一行重新渲染正在发生
  • @TJ getNotificationData 是我们拥有的一个默认函数,它执行 ajax 调用,成功时是一个带有响应的回调

标签: vue.js reactive


【解决方案1】:

您可以使用nextTick。它允许您在更改数据并且 VueJS 根据您的数据更改更新 DOM 之后,但在浏览器在页面上呈现这些更改之前执行某些操作。

【讨论】:

  • 你能给我一个nextTick的例子吗
【解决方案2】:

尝试将this.onSuccess 更改为this.onSuccess.bind(this)onSuccesswindow.restEntity 中作为回调调用时可能会丢失上下文

【讨论】:

  • 实际上上下文并没有丢失,因为我调试并注意到数据属性实际上正在设置,但是有些如何没有重新渲染,并且在模板中我实际上是在这个数据上运行一个循环 getNotificationData
【解决方案3】:

大概您的作业正在失去displayedNotification 的反应性增强功能。我会尝试使用传播操作:

onSuccess(response) {
    this.displayedNotification = { ... response.data};
}

$set 应该有同样的效果,但是因为你想设置整个数组,而不是单个数组元素,所以使用起来会有点困难:

onSuccess(response) {
    this.displayedNotification.splice(0); // empty the array
    response.data.forEach((val, idx) => this.$set(this.displayedNotification , idx, val));
}

【讨论】:

    猜你喜欢
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2020-08-26
    • 2023-04-09
    • 2020-09-18
    • 2018-10-14
    相关资源
    最近更新 更多