Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing v-model attribute name in Vue components

Tags:

vue.js

We're creating an in-house web development framework in our company. We're in the process of creating a component library on top of Vue. Later some other web development frameworks are going to be supported, like React. etc. We do this by encapsulating simple form controls in our own Vue components and use them like this in templates:

<our-input v-model="customerModel" />

What we want to do is, rename the "v-model" prop name to something else, to further abstract away any references to Vue so we can switch to another framework easily.

Any ideas of how to do it other that search and replace?

like image 347
Élodie Petit Avatar asked Oct 12 '17 07:10

Élodie Petit


1 Answers

In Vuejs 2.2 you can now rename value to some other property (source)

Inside component:

Vue.component('OurInput', {
  model: {
    prop: 'customer',
    event: 'change'
  },
  props: {
    // use `customer` as the prop to take the place of `value`
    customer: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  // ...
})

Two way binding using v-model:

<our-input v-model="customerModel" />

Two way binding without using v-model :

<our-input :customer="customerModel" @change="val => { customer = val }"/>

Don't forget to emit change event inside component or just use field input event instead:

this.$emit('close');
like image 50
dwp4ge Avatar answered Nov 15 '22 12:11

dwp4ge