I have a Form
component which renders 3 InputContainer
components. I want to access the value of the input
element on the submit
event of the form. Right now, my submitResource
function logs the div
which contains both label
and input
element.
If not necessary, I don’t want to emit any events with @change handler. The only way I’ve managed to access the input
element is by console.log(titleRef.value.$el.querySelector('input'));
but I think its not the right way to do it.
Thank you!
Form.vue
<template>
<form @submit.prevent="submitResource">
<InputContainer ref="titleRef" />
<InputContainer ref="descriptionRef"/>
<InputContainer ref="linkRef" />
<BaseButton type="submit" class="submit">Add Resource</BaseButton>
</form>
</template>
<script setup>
import BaseButton from './BaseButton.vue';
import InputContainer from './InputContainer.vue';
import { ref } from 'vue';
const titleRef = ref(null);
const descriptionRef = ref(null);
const linkRef = ref(null);
const submitResource = () => {
console.log(titleRef.value.$el);
};
</script>
InputContainer.vue
<template>
<div class="input-container">
<label for="example">Example</label>
<input
type="text"
id="example"
name="example"
/>
</div>
</template>
2
Answers
You can use
defineExpose
to forward a ref from the child.InputContainer.vue:
Then, you can access it in
Form.vue
.If it helps, the typical way to do this in Vue is through two-way binding with
v-model
. For this to work, you build your input components to receive a value through the:modelValue
prop and have them emit an@update:modelValue
event:Form.vue
InputContainer.vue
This approach has several benefits, among them is: