How to use v-model with objects for custom components

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:

  1. Define a custom component that accepts an object as a prop and emits an input event to update the object:



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.

  1. Use the custom component with v-model in the parent component:



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

你可能感兴趣的:(web,vue)