v-model binding an object, the internal components are responsible for the different fields of the scene to achieve

We know that v-model is useful for two-way data binding a single property, maintain data transfer and synchronization between father and son components, but also want a component can handle more data fields under a lot of scenes, then there are some little tricks up .

https://simonkollross.de/posts/vuejs-using-v-model-with-objects-for-custom-components

For example, the following createCustomer components:

<template>
  <div>
    <div>
      <label>Name</label>
      <input type="text" :value="value.name" @input="update('name', $event.target.value)">
    </div>
    <div>
      <label>Type</label>
      <select :value="value.type" @input="update('type', $event.target.value)">
        <option value="Person">Person</option>
        <option value="Company">Company</option>
      </select>
    </div>
  </div>
</template>
<script>
export default {
  props: ['value'],
  methods: {
    update(key, value) {
      this.$emit('input', { ...this.value, [key]: value })
    },
  },
}
</script>

Use components:

<CreateCustomer v-model="{ name: 'John Doe', type: 'Person' }"></CreateCustomer>

 

Guess you like

Origin www.cnblogs.com/kidsitcn/p/11769579.html