點燈坊

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

Preparing Body Object for fetch()

Sam Xiao's Avatar 2022-11-09

When using fetch() for REST POST, we can easily prepare Body Object on Vue.

Version

Vue 3.2

ref()

body000

The body Object is shown.

<template>
  <input v-model='id'>
  <input v-model='name'>
  <button @click='onClick'>Submit</button>
</template>

<script setup>
import { ref } from 'vue'

let id = ref(0)
let name = ref('Sam')

let onClick = () => {
  let body = {
    id: id.value,
    name: name.value
  }

  console.log(body)
}
</script>

Line 2

<input v-model='id'>
<input v-model='name'>
<button @click='onClick'>Submit</button>
  • v-model:two-way data binding the input value to the state
  • @click:fire onClick() on click event

Line 10

let id = ref(0)
let name = ref('Sam')
  • Use ref() to define id and name reactive reference

Line 13

let onClick = () => {
  let body = {
    id: id.value,
    name: name.value
  }

  console.log(body)
}
  • Prepare body Object. Since id and name are Reactive References, we have to use .value to get real value

reactive()

<template>
  <input v-model='state.id'>
  <input v-model='state.name'>
  <button @click='onClick'>Submit</button>
</template>

<script setup>
import { reactive } from 'vue'

let state = reactive({
  id: 0,
  name: 'Sam',
})

let onClick = () => {
  let body = state
  console.log(body)
}
</script>

Line 2

<input v-model='state.id'>
<input v-model='state.name'>
<button @click='onClick'>Submit</button>
  • v-model:two-way data binding the input value to the state, student is a Reactive Object
  • @click:fire onClick() on click event

Line 10

let state = reactive({
  id: 0,
  name: 'Sam',
})
  • Use reactive() to define student Reactive Object. id and name states are just properties of the Object

Line 15

let onClick = () => {
  let body = state
  console.log(body)
}
  • student Reactive Object is the body Object, and we don’t have to prepare the body Object again

Conclusion

  • If we only have a few states, both ref() and reactive() work. But if we have too many states, reactive() is more concise