Vue3 reactive() done right

Vue3 reactive() done right

Reactivity to JSON object in Vue.js

·

2 min read

ref() and reactive() are the two methods for introducing reactivity to your Vuejs application. I didn't face any challenges to introduce reactivity to simple variable types. But this was not true for JSON object or object variable types.

Even though Vuejs documentation provides lots of examples, it was not easy to implement the reactivity for object variable types alas JSON type variables. After I spent many hours of reading and trying different approaches, I finally nailed the simple way for introducing reactivity to JSON-type variables.

Usecase scenario

  • Fetch data from external APIs
  • Bind the JSON response back to the UI layer

Code samples

<script>
import { reactive, toRefs } from 'vue'
import ProductStore from '../store/ProductStore'
export default {
  setup() {
    let state = reactive({
      pinned: {}
    })

    ProductStore.pinned()
    .then((res) => {
      state.pinned = res
    })

    return {
      ...toRefs(state),
      state
    }
  }
}
</script>
  • ProductStore is a simple Javascript API that talks to the server to fetch the data
  • the 'state' is a reactive object that holds 'pinned' JSON object
  • toRefs is for deconstructing the state object for easy access in our UI template
<template>
  <div>
    Pinned Product
    {{ pinned }}
  </div>
</template>
  • Now the pinned JSON object can be easily attached with the UI template
  • This way the JSON response from the server will be bound with the UI with reactive behavior

I believe this article has given you clarity on how to add the reactivity functionality with a JSON object in your vuejs application.

Happy Coding!

Did you find this article valuable?

Support Tham by becoming a sponsor. Any amount is appreciated!