Subscribe on changes!

shallowReactive inside a reactive object is not respected when the property is reassigned

avatar
Jan 16th 2022

Version

3.2.26

Reproduction link

SFC Playground

Steps to reproduce

  • click add
  • click reset
  • click add

What is expected?

I expect the values of the state.data array to always be non-reactive

What is actually happening?

Values inside the array are not reactive only the first time. When a new shallow reactive array is assigned, then its values become reactive.

avatar
Jan 17th 2022

when initialized reactive({...}) state, preserved the shallow proxy

  const getData = () => shallowReactive([{ id: 1 }])
  const state = reactive({ data: getData() })

however the data property is part of a reactive object, and when you set that property with a new shallowReactive object, vue removed the shallow proxy, and made it part of the reactive object.

your expectation to respect shallowReactive, will actually violate the reactive object principles where *everything is suppose to be deeply reactive. with some exceptions for example objects marked as raw

my recommendation will be not to mix the two. but if you really need this use case, you can "protect" it with a ref

  const getData = () => shallowRef(shallowReactive([{ id: 1 }]))
  const state = reactive({ data: getData() })