vuejs / vue

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core
http://v2.vuejs.org
MIT License
207.98k stars 33.69k forks source link

Add custom v-model modifiers #3666

Closed ecmel closed 8 years ago

ecmel commented 8 years ago

We have .lazy, .number, .trim and .undef is on the way.

Apart from .lazy they all work like two-way filters.

Since 2.0 does not support 2 way filters, may be there should be a new api to add custom v-model modifiers to fulfill the same need.

jeankvd commented 5 years ago

Can this be reopened please? A custom directive may work in some cases but behavior can be funny, example:

Vue.directive('number', {
  update: function(el, binding, vnode) {
    el.value = el.value.replace(/[^\d.]/g, '');
  },
});

If you add this directive (along with a v-model) and type letters really fast every other keystrokes the v-model will get out of sync with el.value. And since you cannot modify the binding object you receive there is no way to "reimplement" v-model inside this directive

rkingon commented 5 years ago

@jeankvd I know it feels like overkill, but a wrapper component is going to be the most reliable (see example above).

a wrapper component will allow you to "do more" as well. In your "number" example, ideally, the v-model actually becomes a Number. In your approach, it is still a String.

What if you want to customize the empty value? Empty String? Null? Undefined? -- you can pass in a prop for emptyValue and set it as such.

While once an advocate for this, I realized shortly after modifiers have way too many limitations and just having a component is far superior (at least imo).