8

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.

1 Answer 1

6

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:

<input type="text" :value="message" @input="getModel">

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.