Reactivity with Vue 3

I love Vue! I know I am not alone but it does feel like React still gets most of the attention these days. But I am not here to argue about which better. If you are curious about Vue and want to learn about some ways to keep data in sync, this one is for you.

Vue offers a handful of ways to track dependencies and react to changes in application state. Sometimes the amount of choices can make it a little bit harder to decide. Well, sometimes, often, there are multiple ways to do the same thing!

The Composition API

If you've heard of Vue, but never used it. You may have seen snippets of code that look like this:

<script>
export default {
  data(){
    cats: [
      {
        id: 1,
        name: 'kira',
        yearBorn: 2011
      }
    ]
  },
  ...
}
</script>

This is piece of Vue code, written with the Options API. This is how all Vue used to look up until the release of v3, which introduced the Composition API. That same code, with the composition API could look like:

<script setup>
import { ref } from 'vue'
const cats = ref([{
  id: 1,
  name: 'kira',
  yearBorn: 2011
}])
</script>

The composition API is a more flexible and composable way of working with Vue. I always tell React devs that it is closer to React than before.

Making it reactive

ref() and reactive()

Computed Properties

computed()

To understand the power of computed properties, we first have to talk about props. Like many javascript frameworks. Components data is uni-directional. Parents pass data to their children, and if you need to go the opposite direction, it is not as simple. The data that is passed from parent to child most commonly with props.

Watching for changes with watchers

watch() and watchEffect()

Provide/Inject to reduce Prop Drilling

provide() and inject()