VueJS2 Policy Update

0

I have a problem in my Money directive, it works like this: I make an Axios call to my API, the API brings me a value and I format it to the default BR. But now I had to create a atualizar button that is bringing me this formatting problem. Does anyone know how to make this work please?

  

It is expected that when you click the getNewValue button, the test value is updated and formatted correctly

JSFiddle: HERE

HTML

<div id="app">
<span v-money>{{test}}</span>
<button @click="getNewValue()">Get New Value</button>
</div>

JS

    const formatNumber = (el) => {

   let valorFinal = el.innerHTML;

   if(valorFinal.includes(',')) valorFinal = valorFinal.replace(/\./g, "").replace(',','.'); 

   el.innerHTML = parseFloat(valorFinal).toLocaleString('pt-BR', {minimumFractionDigits: 2,maximumFractionDigits: 2});
};

Vue.directive('money', {
   inserted: function (el) {
      let waitingAPI = setInterval(function () {
         if (el.innerHTML != null && el.innerHTML != '') {
            clearInterval(waitingAPI);
            formatNumber(el);
         }
      }, 300);
   },
   update(el){
       formatNumber(el);
   }
})

const demo = new Vue({
  el: '#app',

  data:{
    test: 10.25
  },
  methods:{
    getNewValue(){
      setTimeout( () => {
        alert('Response Success API!')
        this.test = 1300.25
      },1000)
    }
  }

});

Thank you in advance:)

    
asked by anonymous 02.04.2018 / 22:31

1 answer

1

try to set the value to be formatted as a policy value.

var intl = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' })
Vue.directive('money', {
  bind: function (el, binding) {
    el.innerHTML = intl.format(binding.value)
  },
  update: function (el, binding) {
    el.innerHTML = intl.format(binding.value)
  }
})

new Vue({
  el: "#app",
  data: function () {
    return {
      valor: 10.25
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script><divid="app">
  <label>
    Valor:
    <input type="text" v-model="valor" />
  </label>
  <span v-money="valor"></span>
</div>

However, based on your example, I believe that a filter is more appropriate

var intl = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' })
Vue.filter('money', function (value) {
  return intl.format(value)
})

new Vue({
  el: "#app",
  data: function () {
    return {
      valor: 10.25
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script><divid="app">
  <label>
    Valor:
    <input type="text" v-model="valor" />
  </label>
  <span>{{valor | money}}</span>
</div>
    
03.04.2018 / 16:18