Subscribe on changes!

在method中异步更新数组中的数据,不能及时响应式的渲染到dom中。

avatar
Oct 24th 2020

Version

3.0.2

Reproduction link

https://github.com/Tzdy/vue-next-issues

Steps to reproduce

<template>
    <div>
        <h1 @click="addItem">click</h1>
        <div v-for="(item, index) in items" :key="index">
            {{ item.text }}
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            items: []
        }
    },
    methods: {
        addItem() {
            let item = {
                text: 'apple'
            }
            this.items.push(item)
            setTimeout(() => {
                item.text = 10
            }, 1)
        }
    }
}
</script>

What is expected?

当我点击click时,触发addItem事件,dom中增加一个<div>apple</div>并迅速变为<div>10</div>

What is actually happening?

1,在vue实例中text已经变为10,但是dom中仍然是<div>apple</div> 2,再次点击时,上次增加的<div>apple</div>会变为<div>10/<div>。


在vue2中是正常的

avatar
Oct 24th 2020
avatar
Oct 24th 2020

@unbyte

const app = Vue.createApp({
        data() {
            return {
                items: []
            }
        },
        methods: {
            addItem() {
                let item = {
                    text: 'apple'
                }
                this.items.push(item)
                setTimeout(() => {
                    item.text = 10
                }, 1)
            }
        }
    })
    app.mount('#app')

用这个,或者,直接运行我的例子

avatar
Oct 24th 2020

我的意思是你的用法不对,像我这样写

avatar
Oct 24th 2020

好吧,懂了

avatar
Oct 24th 2020

vue2 会把你原对象做改动,vue3 不会,所以你加入一个非响应式的对象变化不会被追踪

avatar
Oct 24th 2020

Closing as this is an expected difference between Vue 2 and Vue 3