I’m trying to send ID of selected option to my parent component. Also, when the value of my dropdown changes I want to toggle some of my dropdowns to stop being disabled.
This is my custom dropdown component:
<template>
<select
@input="$emit('input', $event.target.value)"
v-bind="$attrs"
@change="change"
>
<option :value="null" disabled selected>
{{ placeholder }}
</option>
<option v-for="option in options" :key="option.id" :value="option">
{{ option.model }}
</option>
</select>
</template>
The problem is that I should send the ID of my option (option.componentable_id), but if I handle value change here then my logic in parent component won’t work.
Currently, my parent component has this:
<Dropdown
placeholder="Odaberi matičnu ploču"
:options="motherboards"
hardcoded-value="First option"
class="pc-builder-sixth-background"
:change="setIsMotherboardChosen"
/>
Relevant to that, I have 2 dropdowns that are being enabled or disabled depending on this state:
<Dropdown
placeholder="Odaberi RAM memoriju"
:options="rams"
hardcoded-value="First option"
class="pc-builder-fourth-drodpown"
:disabled="!isMotherboardChosen"
/>
Function to set my value is here:
function setIsMotherboardChosen() {
isMotherboardChosen.value = !isMotherboardChosen.value;
console.log(isMotherboardChosen.value);
}
I know currently the code isn’t so clean, but I just want to send my id and toggle value in the same time. I tried different types of binds etc. but the problem is that I have to do 2 things in different files so I’m struggling. I have managed to make disabling logic, but I don’t know how to connect it with my ID API logic.
2
Answers
At this point, it would be better and easier to use
v-mount
attribute and bind it to a ref. It should work the same for your componentYou can find more about handling forms in the vue documentation
You’re not listening for any events in the parent.
To listen to the input event you should use
@input
, and the method you want to call when the event is captured:Even better though would be to use v-model as this is the exact situation that it’s meant for (two-way binding)
Parent
Child
This way, whenever a dropdown option is selected,
motherboardOption
in the parent will have that value immediately assigned to it, meaning the option id will be accessible asmotherboardOption.id
, and you can still use this value when setting your:disabled
props:Vue Playground example