父组件:
<template>
<CustomInput v-model="message.person" /> {{ message}}
</template>
<script>
import CustomInput from './CustomInput.vue'
export default {
components: { CustomInput },
data() {
return {
message: {name:'',person:{username:'zhangsan',userid:'1234'}}
}
}
}
</script>
子组件:文章来源:https://www.toymoban.com/news/detail-733080.html
<template>
<input :value="modelValue.username" @change="handleChange" />
<input :value="modelValue.userid" @change="handleChange1" />
</template>
<script>
export default {
props: ['modelValue'],
emit: ['update:modelValue'],
setup(props,{emit}) {
const handleChange = (event) => {
emit('update:modelValue', { ...props.modelValue, username: event.target.value});
}
const handleChange1 = (event) => {
emit('update:modelValue', { ...props.modelValue, userid: event.target.value});
}
return { handleChange ,handleChange1 }
}
}
</script>
如使用element-plus写法如下:
<template>
<el-input v-model="modelValue.username" @change="handleChange"/>
<el-input v-model="modelValue.userid" @change="handleChange1"/>
</template>
<script>
export default {
props: ['modelValue'],
emit: ['update:modelValue'],
setup(props,{emit}) {
const handleChange = (event) => {
emit('update:modelValue', { ...props.modelValue, username: event});
}
const handleChange1 = (event) => {
emit('update:modelValue', { ...props.modelValue, userid: event});
}
return { handleChange ,handleChange1 }
}
}
</script>
在实际运用中不需要这么复杂,父组件不变,子组件如下文章来源地址https://www.toymoban.com/news/detail-733080.html
<template>
<el-input v-model="modelValue.username" @change="handleChange"/>
<el-input v-model="modelValue.userid" @change="handleChange1"/>
</template>
<script>
export default {
props: ['modelValue'],
setup(props) {
const handleChange = (event) => {
//具体逻辑 例如:修改父组件username的值
props.modelValue.person.username = 'lisi'
props.modelValue.person.username = props.modelValue.person.username.slice(0,2)
}
const handleChange1 = (event) => {
//具体逻辑
}
return { handleChange ,handleChange1 }
}
}
</script>
到了这里,关于vue3父子组件传对象,子组件访问修改父组件对象中的属性值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!