Although we use const
as the modifier for an Object, we can still modify its property. readonly
comes to the rescue of semantic.
Version
Vue 3.2
Mutable Object
<script setup>
const obj = { name: 'Sam' }
obj.name = 'Tom'
console.log (obj)
</script>
obj
is defined as const
, but we can still modify the value of name
property.
Immutable Object
<script setup>
import { readonly } from 'vue'
const obj = readonly ({ name: 'Sam' })
obj.name = 'Tom'
console.log (obj)
</script>
Use readonly
with Object, and it will return a readonly proxy. We can not modify the value of name
property. It is a real const
in semantic.
WebStorm knows readonly
and gives us a warning.
@vue/reactivity
import { readonly } from '@vue/reactivity'
const obj = readonly ({ name: 'Sam' })
obj.name = 'Tom'
console.log (obj)
If we want to use readonly
on the backend, we can import readonly
from @vue/reactivity
.
Conclusion
- We can use
Object.freeze
to simulate an immutable object but only shallow. Vue’sreadonly
is deep : any nested property accessed will be readonly as well - Not only using
readonly
on the frontend, but also the backend