When using fetch()
for REST POST, we can easily prepare Body Object on Vue.
Version
Vue 3.2
ref()
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
:fireonClick()
onclick
event
Line 10
let id = ref(0)
let name = ref('Sam')
- Use
ref()
to defineid
andname
reactive reference
Line 13
let onClick = () => {
let body = {
id: id.value,
name: name.value
}
console.log(body)
}
- Prepare
body
Object. Sinceid
andname
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
:fireonClick()
onclick
event
Line 10
let state = reactive({
id: 0,
name: 'Sam',
})
- Use
reactive()
to definestudent
Reactive Object.id
andname
states are just properties of the Object
Line 15
let onClick = () => {
let body = state
console.log(body)
}
student
Reactive Object is thebody
Object, and we don’t have to prepare thebody
Object again
Conclusion
- If we only have a few states, both
ref()
andreactive()
work. But if we have too many states,reactive()
is more concise