Observing a getter for a property of an object. Here's an illustration showcasing how to declare objects using reactive()
and ref()
.
vue playground
<script setup>
import { ref, reactive, watch } from 'vue'
const msg = ref('Hello World!')
const state1 = reactive({ id: 1, name: "your-name-reactive" })
const state2 = ref({ id: 2, name: "your-name-ref" })
const testingField1 = ref('')
const testingField2 = ref('')
const testingField3 = ref('')
watch(
() => state1.name,
(newName, prevName) => {
testingField1.value = newName
}
)
watch(
() => state2.value.name,
(newName, prevName) => {
testingField2.value = newName
}
)
watch(
[() => state1.name, () => state2.value.name], // ⬅️
() => {
testingField3.value = `was triggered by any one at ${new Date().toLocaleString()}`
}
)
</script>
<template>
<h1>{{ msg }}</h1>
<div>
<input v-model="state1.name" />
<button @click="state1.name = new Date().toLocaleString()">click me</button>
<span>{{ testingField1 }}</span>
</div>
<div>
<input v-model="state2.name" />
<button @click="state2.name = new Date().toLocaleString()">click me</button>
<span>{{ testingField2 }}</span>
</div>
<div>
<span>{{ testingField3 }}</span>
</div>
</template>
It is important to note the usage of .value
when initializing an object with ref()
.