从父组件触发子组件发出的最佳方法是什么?



现在我正在传递从父组件到子组件的trigger prop,它触发从子组件到父组件的emit

parent component:

<form @submit.prevent="state.store=true" method="post" enctype="multipart/form-data">
<child-component :triggerEmit=state.store @emitSomething="getSomething()"/>

child component:

const emit = defineEmits([
'emitBody'
])
watchEffect(async () => {
if (props.triggerEmit) {
emit('emitSomething', value)
}
})

这很快就会让人困惑,如果组件的大小增长,我想知道是否有一种更简单的方法从父级触发child emits,因为这似乎是一个常见的用例。

编辑:

尝试直接从父进程触发child method(不工作)。

child:

const childMethod = () => {
console.log('check')
}

parent:

html:

<child ref="childRef"/>

脚本设置:

const childRef = ref()
childRef.value.childMethod()

Page抛出错误:

Cannot read properties of undefined (reading 'childMethod')

根据我的理解,您希望从父组件访问多个子组件方法/属性。如果是,您可以通过创建ref并访问方法来实现。

模板:

<!-- parent.vue -->
<template>
<button @click="$refs.childComponentRef.childComponentMethod()">Click me</button>
<child-component ref="childComponentRef" />
</template>

脚本:

With Vue 2:

this.$refs.childComponentRef.childComponentMethod( );

With Vue 3 Composition Api:

setup( )
{
const childComponentRef = ref( );
childComponentRef.value.childComponentMethod( )
return {
childComponentRef
}
}  

在这种情况下,父触发器有效地查询子触发器的事件数据,以便它可以调用getSomething()。父进程已经拥有getSomething(),所以它实际上只需要子进程的数据。

另一种获取数据的方法是使用v-model来跟踪子数据:

  1. 在子组件中,通过声明一个modelValueprop并发出一个带有新值作为事件数据的'update:modelValue'事件,为prop(例如字符串)实现v-model:
<!-- ChildName.vue -->
<script setup>
defineProps({ modelValue: String })
defineEmits(['update:modelValue'])
</script>
<template>
<label>Name
<input type="text" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</label>
</template>
  1. 在父对象中,添加一个reactive对象,包含每个子v-model的字段:
<!-- ParentForm.vue -->
<script setup>
import { reactive } from 'vue'
const formData = reactive({
name: '',
age: 0,
address: {
city: '',
state: '',
},
})
</script>
<template>
<form>
<child-name v-model="formData.name" />
<child-age v-model="formData.age" />
<child-address v-model:city="formData.address.city" v-model:state="formData.address.state" />
<button>Submit</button>
</form>
</template>
  1. 现在,父类可以在提交表单时对每个字段调用getSomething():
<!-- ParentForm.vue -->
<script setup>
import { toRaw } from 'vue'
⋮
const getSomething = field => {
console.log('getting', field)
}
const submit = () => {
Object.entries(toRaw(formData)).forEach(getSomething)
}
</script>
<template>
<form @submit.prevent="submit">
⋮
</form>
</template>

演示

最新更新