在method中异步更新数组中的数据,不能及时响应式的渲染到dom中。
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中是正常的
use reactive
https://codepen.io/unbyte/pen/xxOgQOE
@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')
用这个,或者,直接运行我的例子