As per my understanding both ref
and reactive
are Composition API methods.
ref
is used to create reactive object for a single reactive variable like String
or Number
. ref values are accessed using the .value property.
reactive
, on the other hand, is used to create a reactive object that can contain multiple values. reactive
objects value are accessed directly as objects.
Since both ref
and reactive
are ways of creating reactive data, what is the key difference between them other than primitive vs complex object, and why do we have both?
I am learning Vuejs and I tried the below code sample to under ref and reactive.
<script>
import { ref, reactive } from 'vue';
export default {
setup() {
const counter = ref(0);
const counterObj = reactive({counter: 0});
function increment() {
counter.value++;
counterObj.counter++;
}
return {
counter, counterObj, increment,
}
}
}
</script>
<template>
<button @click="increment">click me</button>
<span>{{ counter }} {{counterObj.counter}}</span>
</template>