What's the proper way to implement formatting on v-model in Vue.js 2.0

前端 未结 4 1379
耶瑟儿~
耶瑟儿~ 2021-02-05 02:45

For a simple example: textbox to input currency data. The requirement is to display user input in \"$1,234,567\" format and remove decimal point.

I have tried vue direct

4条回答
  •  感情败类
    2021-02-05 03:34

    Using Vue custom directives + .toLocaleString() is also a very good option.

    Vue.directive("currency", {
      bind(el, binding, vnode) {
        el.value = binding.value && Number(binding.value).toLocaleString('en-US', {style: 'currency', currency: !binding.arg ? 'USD' : binding.arg });
        el.onblur = function(e) {
          e.target.value = Number(e.target.value).toLocaleString('en-US', {style: 'currency', currency: !binding.arg ? 'USD' : binding.arg});
        };
        el.onfocus = function(e) {
          e.target.value =
            e.target.value && Number(e.target.value.replace(/[^\d.]/g, ""));
        };
        el.oninput = function(e) {
          vnode.context.$data[binding.expression] = e.target.value;
        };
      }
    });
    

    Here is the example link: https://codepen.io/Mahmoud-Zakaria/pen/YzPvNmO

提交回复
热议问题