En este momento, estoy pasando un trigger prop del componente principal al secundario, que activa la emit del elemento secundario al principal.
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) } }) Esto se vuelve confuso rápidamente, si los componentes aumentan de tamaño y me preguntaba si hay una forma más sencilla de activar child emits del padre, ya que este parece ser un caso de uso común.
Editar :
Intentando activar el child method directamente desde el padre (no funciona).
child :
const childMethod = () => { console.log('check') } parent :
html:
<child ref="childRef"/>configuración del guión:
const childRef = ref() childRef.value.childMethod()La página arroja un error:
Cannot read properties of undefined (reading 'childMethod')Según tengo entendido, desea acceder a múltiples métodos/propiedades de componentes secundarios desde el componente principal. En caso afirmativo, puede lograrlo creando una referencia y accediendo a los métodos.
En plantilla :
<!-- parent.vue --> <template> <button @click="$refs.childComponentRef.childComponentMethod()">Click me</button> <child-component ref="childComponentRef" /> </template>En guión :
Con Vue 2 :
this.$refs.childComponentRef.childComponentMethod( );Con Vue 3 Composición Api :
setup( ) { const childComponentRef = ref( ); childComponentRef.value.childComponentMethod( ) return { childComponentRef } }En este caso, el activador del elemento primario consulta efectivamente al elemento secundario los datos de su evento para que pueda llamar a getSomething() en él. El padre ya posee getSomething() , por lo que realmente solo necesita los datos del hijo.
Otra forma de obtener esos datos es usar v-model para rastrear los datos secundarios:
v-model para una propiedad (una cadena, por ejemplo) declarando una propiedad modelValue y emitiendo un evento 'update:modelValue' con el nuevo valor como datos del evento: <!-- 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>reactive , que contenga un campo para el v-model de cada hijo: <!-- 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>getSomething() en cada campo al enviar el formulario: <!-- 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>