How to use v-model with objects for custom components

2023-12-16 17:07:54

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:
<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.

  1. Use the custom component with 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

文章来源:https://blog.csdn.net/yuguo_im/article/details/134924217
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。