If an Object is modified, we want the HTML to be updated accordingly. We may use reactive()
or ref()
to create the Object.
Version
Vue 3.2
reactive()
We have defined some default values for Reactive Object by reactive()
. But the Object is modified by onMounted()
.
<template>
<div>ID:<input v-model="student.id" /></div>
<div>Name:<input v-model="student.name" /></div>
</template>
<script setup>
import { reactive, onMounted } from 'vue'
let student = reactive({
id: 0,
name: 'Sam'
})
onMounted(() => {
let data = {
id: 1,
name: 'John'
}
Object.assign(student, data)
})
</script>
Line 2
<div>ID:<input v-model="student.id" /></div>
<div>Name:<input v-model="student.name" /></div>
v-model
:ID
andName
is binding tostudent
Reactive Object, not Reactive Reference
Line 9
let student = reactive({
id: 0,
name: 'Sam'
})
reactive()
:definestudent
Reactive Object
Line 14
onMounted(() => {
let data = {
id: 1,
name: 'John'
}
Object.assign(student, data)
})
Object.assign()
:assign whole newdata
Object tostudent
We can’t use
student = data
to assign a new Object to a Reactive Object. It won’t fire the reactivity to change the HTML
ref()
<template>
<div>ID:<input v-model="student.id" /></div>
<div>Name:<input v-model="student.name" /></div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
let student = ref({
id: 0,
name: 'Sam'
})
onMounted(() => {
let data = {
id: 1,
name: 'John'
}
student.value = data
})
</script>
Line 2
<div>ID:<input v-model="student.id" /></div>
<div>Name:<input v-model="student.name" /></div>
v-model
:ID
andName
are binding tostudent
Reactive Reference to Object, not Reactive Object. But the syntax is the same
Line 9
let student = ref({
id: 0,
name: 'Sam'
})
ref()
:definestudent
Reactive Reference to Object
Line 14
onMounted(() => {
let data = {
id: 1,
name: 'John'
}
student.value = data
})
- We can just use
=
to assign a whole newdata
Object tostudent
We can also use
Object.assign()
to assign a new Object
Conclusion
- As for Reactive Object, we may want to use
reactive()
. But there are some restrictions onreactive()
. We can only useObject.assign()
to assign a new Object - We may also use
ref()
for Reactive Reference to an Object.=
orObject.assign()
both remains the Reactivity