In Vue.js, the v-model
directive is commonly used for two-way data binding between a parent component and a child component. By default, v-model
works with primitive values like strings or numbers. However, you can also use v-model
with objects in custom components by leveraging the value
and input
event bindings.
Here’s an example of how you can use v-model
with objects in custom components:
input
event to update the object:<template>
<div>
<input v-model="internalValue.name" @input="updateValue" />
<input v-model="internalValue.age" @input="updateValue" />
</div>
</template>
<script>
export default {
props: {
value: {
type: Object,
required: true
}
},
data() {
return {
internalValue: { ...this.value }
};
},
methods: {
updateValue() {
this.$emit("input", { ...this.internalValue });
}
}
};
</script>
In this example, the custom component accepts an object as a prop named value
. We create an internalValue
data property and initialize it with a copy of the prop value. The v-model
directive is used on the input fields to bind to the corresponding properties of internalValue
. When the input value changes, the updateValue
method is called, which emits an input
event with a copy of internalValue
.
v-model
in the parent component:<template>
<div>
<custom-component v-model="myObject"></custom-component>
<pre>{{ myObject }}</pre>
</div>
</template>
<script>
import CustomComponent from "@/components/CustomComponent.vue";
export default {
components: {
CustomComponent
},
data() {
return {
myObject: {
name: "",
age: null
}
};
}
};
</script>
In the parent component, we import the custom component and register it. We define a myObject
data property with the initial values for name
and age
. By using v-model
on the custom component, the myObject
property is automatically passed as the value
prop to the custom component, and the input
event is handled to update myObject
when the input fields change.
With this setup, changes made in the custom component’s input fields will be reflected in the parent component’s myObject
property, and vice versa.
By following this pattern, you can use v-model
with objects in custom components in Vue.js, enabling two-way data binding for more complex data structures.
If you want to know more about the usage of nested objects, please refer to the following blog:
Vue.js: Using v-model with objects for custom components