點燈坊

失くすものさえない今が強くなるチャンスよ

Making Reactive Object with reactive() and ref()

Sam Xiao's Avatar 2022-11-15

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()

object000

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-modelID and Name is binding to student Reactive Object, not Reactive Reference

Line 9

let student = reactive({
  id: 0,
  name: 'Sam'
})
  • reactive():define student Reactive Object

Line 14

onMounted(() => {
  let data = {
    id: 1,
    name: 'John'
  }

  Object.assign(student, data)
})
  • Object.assign():assign whole new data Object to student

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-modelID and Name are binding to student Reactive Reference to Object, not Reactive Object. But the syntax is the same

Line 9

let student = ref({
  id: 0,
  name: 'Sam'
})
  • ref():define student Reactive Reference to Object

Line 14

onMounted(() => {
  let data = {
    id: 1,
    name: 'John'
  }

  student.value = data
})
  • We can just use = to assign a whole new data Object to student

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 on reactive(). We can only use Object.assign() to assign a new Object
  • We may also use ref() for Reactive Reference to an Object. = or Object.assign() both remains the Reactivity