ref() creates a reactive object for whatever variable we pass it in. However, it is only preferable if we’re dealing with some primitive values. Like strings, numbers, boolean, etc. For more complex variable types, we want to use the reactive() method instead.
Here’s a small component where we can enter some input. And when we click on the Greet button, we see a greeting. The Reset button clears the input field.
This is how the code with ref() states looks like:
<script setup>
import { ref } from "vue";
const name = ref("");
const greetName = () => alert(`Hello ${name.value}!`);
const clearName = () => name.value = "";
</script>
<template>
<div>
<input v-model="name" type="text" placeholder="Enter name" />
<div class="buttons-container">
<button @click="greetName">Greet</button>
<button @click="clearName">Reset</button>
</div>
</div>
</template>
Code language: HTML, XML (xml)
We can modify the script code to use the reactive system as follows:
<script setup>
import { reactive } from "vue";
const inputData = reactive({
name: ''
})
const greetName = () => alert(`Hello ${inputData.name}!`);
const clearName = () => inputData.name = "";
</script>
<template>
<div>
<input v-model="inputData.name" type="text" placeholder="Enter name" />
<div class="buttons-container">
<button @click="greetName">Greet</button>
<button @click="clearName">Reset</button>
</div>
</div>
</template>
Code language: HTML, XML (xml)
As you can see, we can now access the name property using the inputData.name directly. This has 2 major advantages over using the ref() state system:
- Instead of using this.<propertName>for script and <propertyName> in template, we can just use <objectName>.<propertyName> everywhere!
- We can group together relevant data easily with multiple objects instead of multiple properties