How to get a raw object from a reactive variable in Composition API of Vue 3

Work is a mine of ideas for blog posts. Today, I had an unexpected issue with getting a value of a reactive property. I wanted to get an object but I received Proxy. Please have a look on my code.

<script setup>
import { ref } from 'vue'

const bar = ref({
  id: 1,
  data: {a: 1, b:2, c:3},
})

console.log('bar', bar.value.data)
</script>

In this case, console.log shows a Proxy object. I didn't expect it, because for simple data types, it just shows values.

The solution

Fortunately, the solution is easy. You can just use toRaw(). toRaw() returns a raw object from a reactive property.

<script setup>
import { ref, toRaw } from 'vue'

const bar = ref({
  id: 1,
  data: {a: 1, b:2, c:3},
})

console.log('bar toRaw', toRaw(bar.value.data))
</script>

I prepared the working example where you can check it yourself. You just need to open dev tools in your browser :-)

Comments

Blog Comments powered by Disqus.

Older Post Newer Post