I'm having difficulty to get parent component's property object, with dynamically populated properties to make the values available inside of the same component.
A bit hard to explain, so please have a look at the example below:
Parent Component
<script>
export default {
data() {
return {
fields: {},
}
}
}
</script>
Child Component
<template>
<select
@change="update()"
v-model="field"
>
<option
v-for="option in options"
:value="option.value"
>
{{ option.name }}
</option>
</select>
</template>
<script>
export default {
props: {
initialOptions: {
type: Array,
required: true
}
},
data() {
return {
field: '',
options: this.initialOptions
}
},
mounted() {
if (
(this.field === undefined || this.field === '') &&
this.options.length > 0
) {
this.field = this.options[0].value;
}
this.update();
},
methods: {
update() {
this.$emit('input', this.field);
}
}
}
</script>
DOM
<parent-component inline-template>
<div>
<child-component>
:initial-options="[{..}, {..}]"
v-model="fields.type_id"
></child-component>
</div>
<div :class="{ dn : fields.type_id == 2 }">
// ...
</div>
</parent-component>
Using Vue console I can see that fields
object gets all of the child component models with their associated values as they emit input
when they are mounted, however for some strange reason the :class="{ dn : fields.type_id == 2 }"
does not append the class dn
when the selection changes to 2
. Dom doesn't seem to reflect the changes that are synced between parent and child components.
Any help on how to make it work?
fields
? – Bertv-model
directive on the child component and onmounted
emittinginput
event with associated value from each child component. – Sebastian Sulinskifields
is starting off as an empty object. If you are adding properties to that incorrectly, then Vue will not be able to detect the changes. – BertChild Component
section and thenDOM
where child component getsv-model
. You'll see that onmounted
there is a call toupdate()
method, which emits the event. – Sebastian Sulinskifields: {}
get a property calledtype_id
? – Bert