點燈坊

失くすものさえない今が強くなるチャンスよ

Using readonly to Implement Immutable Object

Sam Xiao's Avatar 2021-12-07

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.

immutable000

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.

immutable003

WebStorm knows readonly and gives us a warning.

immutable001

@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.

immutable002

Conclusion

  • We can use Object.freeze to simulate an immutable object but only shallow. Vue’s readonly is deep : any nested property accessed will be readonly as well
  • Not only using readonly on the frontend, but also the backend

Reference

Vue, readonly