vue3父子组件传对象,子组件访问修改父组件对象中的属性值

父组件:

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

子组件:

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

在实际运用中不需要这么复杂,父组件不变,子组件如下

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

你可能感兴趣的:(前端技巧,javascript,前端,vue.js)