Subscribe on changes!

function中同时改变reactive和shallowReactive中的数据时,shallowReactive的值也会被响应式地更改

avatar
Apr 17th 2022

Version

3.2.13

Reproduction link

sfc.vuejs.org/

Steps to reproduce

    const firstJob = reactive({
        type: 'front end',
        salary: 4000
    })
    const secondJob = shallowReactive({
        type: 'front end',
        salary: {
            baseSalary: 5400,
            commissionSalary: 700
        }
    })
    function incrementSalary () {
        firstJob.salary += 1000
        secondJob.salary.baseSalary += 1000
    }

当incrementSalary函数执行时,shallowReactive定义的变量值也会更改

What is expected?

shallowReactive只做浅层次的响应,不会对深层次的数据造成影响。

What is actually happening?

当同一个function内既改变了reactive定义的值,也改变了shallowReactive的值,这时shallowReactive会失效,也会做出响应式的改变。

avatar
Apr 17th 2022

This is a common misconception, more about template updates than shallowReactive.

When a component updates, the whole template is updates with all the latest data.

You change to the nested shallowReactive() data will not cause a template update. But when something else does cause a template update, then the nested shallowReactive data will also be part of this update.

So: This is expected behavior.

Google translate:

这是一个常见的误解,更多的是关于模板更新而不是 shallowReactive

当组件更新时,整个模板将更新为所有最新数据。

您更改为嵌套的 shallowReactive() 数据不会导致模板更新。 但是当其他事情确实导致模板更新时,嵌套的 shallowReactive 数据也将成为此更新的一部分。

这是预期的行为。