Set v-model value within a slot in Vuejs
Set v-model value within a slot in Vuejs
I have two components
child-component.vue
<template>
</template>
parent-component.vue
<template>
<my-component>
<input type="text" v-model="myinput1">
<input type="text" v-model="myinput2">
<input type="text" v-model="myinput3">
</my-component>
</template>
export default {
data() {
return {
myinput1: '',
myinput2: '',
myinput3: '',
}
}
}
I need to set the values of each input field inside the slot directly from child-component (the number of input fields could change).
Is there a way to achieve it without triggering an event from child component?
Thanks
@Beau yes, but how can I use them in my case?
– Fabio
Jul 3 at 10:01
1 Answer
1
In the child component
<template>
</template>
export default
{
data()
{
return {
slotData: ['1', '2', '3']
};
}
}
In the parent component
<template>
<my-component>
<template slot-scope="props">
<input v-for="item in props.data" type="text" v-model="item">
</template>
</my-component>
</template>
Thanks for your answer, but in my case I don't have a fixed number of input fields. Anyway I upvote your answer because you gave me a good starting point.
– Fabio
Jul 3 at 12:33
Parent component defines how many input fields child component has. What I want is something like looping through all slots and set the value.
– Fabio
Jul 3 at 13:13
Do not forget that Vue has a strict MVVM behavior - data passes from parent to child, events bubble from child to parent. Your best bet is to pass the number (and eventually the type) of inputs to the child and let the child create (and manage) them by itself.
– IVO GELOV
Jul 3 at 13:58
Thanks again. This was my first try, but I prefered to use slots due to the high number of props I had to pass to child component to create my inputs.
– Fabio
Jul 3 at 14:20
If you find yourself in a situation where you are passing too many props - then it is time to rethink and/or reconsider your application architecture. You may need to use a global state manager like Vuex, or implement the child's behavior inside the parent and do not use a child at all. Or perhaps you need a large number of specialized children which already know what kind of input they need to produce. Anyway - we can not see the whole picture as you are seeing it.
– IVO GELOV
Jul 3 at 15:09
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Have you looked into Scoped Slots?
– Beau
Jul 3 at 9:43