【问题标题】:Vue 2; DOM not updating to data change and watcherVue 2; DOM 未更新到数据更改和观察者
【发布时间】:2022-01-09 20:09:51
【问题描述】:

我有一个通过initialCurrentUser 属性的子组件。这从顶级父组件<App> 开始,到子组件Sidebar,最后到孙子组件WindowFavorite

当用户未登录时,变量为null。当它们是时,它是一个对象,其属性包括favorites,这是一个他们最喜欢的条目的数组。

<App>,我有:

<template>
<sidebar
    :initial-current-user="currentUser">
    </sidebar>
</template>

...

export default {
    name: "App",
    ...
    data() {
        return {
            currentUser: null,
        };
    },
   methods: {
   ...
   getUser() { // sets this.currentUser on login success}
   }


&lt;Sidebar&gt; 中,我将数据属性设置为initialCurrentUser,调用currentUser,并将其传递给子WindowFavorite

然后在Sidebar 上的观察者中,我有:

 initialCurrentUser: {
            handler: function( val ) {
                this.currentUser = val;
            },
            immediate: true
        }

&lt;Sidebar&gt; DOM 元素正在对这一变化做出反应。但是当我传递给&lt;WindowFavorite&gt; 时,DOM 中的循环正在检查null 值上的favorites 属性。即使 currentUser 正在更新(我在 Vue 开发工具中看到它已更新),DOM 仍然认为它是 null

template>
  <div>
    
        <div v-for="favorite in currentUser.favorites" :key="favorite.id" class="py-6 border-b border-brand-mint-muted-alt">
           

        </div>
      

 
  </div>
</template>

<script>


export default {
    name: "WindowFavorites",
    components: {
        
    },
    data() {
  
        return {
            currentUser: this.initialCurrentUser
        };
    },

    props: {
        initialCurrentUser: {
            default: null,
            type: Object
        }

    },
    
    mounted() {
 
    },
    watch: {
        initialCurrentUser: {
            handler: function( user ) {
                this.currentUser = user;
            }
        }
    },
    computed: {
     
    },
    methods: {

    }
};
</script>


因此,虽然 DOM 认为 currentUser 为空,但实际上是:

{
"id":1,
"favorites":[ {id: 1}, { id: 2}]
}

我不确定为什么 DOM 没有反应。

回顾一下,管理currentUser 的初始更改。它传递给&lt;Sidebar&gt;,然后传递给WindowFavorite&lt;Sidebar&gt; 有一个观察者来观察道具变化并设置自己的currentUser 数据变量,然后使用它传递给 ITS 子道具。

数据似乎在整个组件中更新,并在 Vue 开发工具中正确显示,但是,dom 本身仍然认为更改的变量为空。

一旦发生页面刷新,它就会正确抓取数据。只是没有实际的 javacript 数据更改。

【问题讨论】:

标签: vue.js vuejs2


【解决方案1】:

&lt;Sidebar&gt; 及其&lt;WindowFavorites&gt; 子对象在currentUser 设置在App.vue 之前立即渲染,并且它们的initialCurrentUser 属性都绑定到currentUser,最初是nullWindowFavorites 尝试渲染其模板,引用currentUser.favorites(其中currentUsernull),导致您观察到的错误。即使 currentUser 之后异步更新,null 引用已经发生,阻止任何更新。

一种解决方案是在currentUser 上有条件地渲染WindowFavorites

<!-- Sidebar.vue -->
<WindowFavorites v-if="currentUser" :initial-current-user="currentUser" />

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-24
    • 2021-08-04
    • 2015-08-23
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多