Vue js apply filter on v-model in an input field

前端 未结 7 1684
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 22:37

Hope someone can help me! I have made a directive wrapping the Jasny Bootstrap Plugin more specifically the input-mask thing and everything goes well!

Now I have made a

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-03 23:06

    I had a similar problem when I wanted to uppercase an input value.

    This is what I ended up doing:

    // create a directive to transform the model value
    Vue.directive('uppercase', {
      twoWay: true, // this transformation applies back to the vm
      bind: function () {
        this.handler = function () {
          this.set(this.el.value.toUpperCase());
        }.bind(this);
        this.el.addEventListener('input', this.handler);
      },
      unbind: function () {
        this.el.removeEventListener('input', this.handler);
      }
    });
    

    Then I can use this directive on the input field with a v-model.

    
    

    Now, whenever I type into this field or change someData, the value is transformed to uppercase.

    This essentially did the same thing as I hoped v-model="someData | uppercase" would do. But of course, you can't do that.

    In summation: make a directive that transforms the data, not a filter.

提交回复
热议问题