[Vuejs]-Utility method in Vue.js

0👍

Apparently you can pass the data object reference to the handler method like so:
(Note you can’t just pass the data property, because I don’t believe it will be a reference.)

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    inputs:{
      'v1':{
        value:'1.256'
      },
      'v2':{
        value:'1.521'
      }
    },
    someInput:{value:'1.7125'}
  },
  methods:{
    validateDecimal: function (o,p,e) {
        console.log('validateDecimal',o);
        var val = e.target.value;
        console.log(val);
        if (Number(parseFloat(val)) == val) {
            val = parseFloat(val).toFixed(2);
            this.$set(o, p, val);
        } else {
            this.$set(o, p, '');
            e.target.value = '';
        }
    },
    foo: function(){
      console.log(this.inputs.v1.value)
      console.log(this.inputs.v2.value)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="i,key in this.inputs">
    <input class="ui-input" :value="i.value" placeholder="0.00" @blur="validateDecimal(i, 'value', $event)">
  </div>
  <div>
    <input class="ui-input" :value="this.someInput.value" placeholder="0.00" @blur="validateDecimal(someInput,'value', $event)">
  </div>
  <button @click="foo">Click</button>
</div>

Edit by OP: Adding an extra parameter for the name of the property and using $set to make the dynamic property reactive. This should make the method more general purpose for any dynamic input fields with any property name.

Leave a comment