Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create a v-model modifier to a VueJS Component?

Tags:

vue.js

In VueJS there is some v-model modifies that pre-parse the binded value, for instance v-model.trim that removes whitespaces from the string.

How can I create my own modifier? for instance v-model.myparse Today um using something like:

computed: {
  name: {
    get: function () { return parse(this._name);},
    set: function (value) { _name = parse(value);}
  }

What is very verbose.

I would it to be reusable to do something like:

<input v-model.myparse="name" name='n1'/>
<input v-model.myparse="name" name='n2'/>
<input v-model.myparse="name" name='n3'/>
<input v-model.myparse="name" name='n4'/>

computed properties with setters seems to do part of the work, but it is really useful with some few variables only, it becomes very verbose with a lot of properties.

like image 479
Daniel Santos Avatar asked Mar 31 '18 18:03

Daniel Santos


1 Answers

First, adding adding a custom modified to v-model is under discussion but not yet implemented.

If it was implemented, you could extend the v-model and add a modifier to it.

Since that is not possible, you have a couple of options left, one of which is to use :value instead of v-model. Because v-model is just a syntactic sugar of following:

  <input type="text" :value="message" @input="message = $event.target.value">

The above code is the same as:

  <input type="text" v-model="message">

So, I suggest you replace the logic for the @input to something like this:

Now, you can use a function to return a modified value as:

methods: {
  getModel ($event) {
    return $event.target.value.trim()
  } 
}

But all of what I mentioned can still be done with the v-model if you use a function.

Of course it goes without saying, you can create your own custom directive also.

like image 176
samayo Avatar answered Sep 23 '22 06:09

samayo