The parent component has data that I want to pass to the child component. For example, I created such a component with data.
Parent component
<template>
<NameUser :data="userData"></NameUser>
<div>first name: {{ userData.firstName }}</div>
<div>last name: {{ userData.lastName }}</div>
</template>
<script setup>
import {ref} from 'vue'
import NameUser from '../components/NameUser.vue';
const userData = ref({
firstName: 'testName',
lastName: 'testLastName'
})
</script>
In the child component, I receive this data and will have to pass it back to the parent component after changing it.
Child component
<template>
<label>First name</label>
<input :value="data.firstName" @input="changeData">
<label>Last name</label>
<input :value="data.lastName" @input="changeData">
</template>
<script setup>
const props = defineProps({
data:Object
})
function changeData(){}
</script>
Help to implement the changeData function. Please tell me if it is necessary to use the computed property to avoid re-rendering.
2
Answers
The nicest way I could come up with doing this is as follows
here is a codesdandbox.io working version of the code below
Parent.vue
NameUser.vue
SFC Playground
You can use a separate reactive object inside
NameUser
to update it from inputs and synchronize it with a model value. That way you can add any additional inputs without declaring any extra variables.Also your
changeData
doesn’t receive any extra parameter to distinguish different props in the user object. Usev-model
on inputs instead. Otherwise it’s unnecessarily complicated.NameUser.vue
Parent.vue: