[Vuejs]-Bind input with factor (v-model)

1๐Ÿ‘

โœ…

Try to use Computed property with get/set as mentioned in VueJS documentation.

something like this:

const factor = 3.141/360;

new Vue({
  el: "#app",
  data: {
    internalValue: '',
  },
  computed: {
    value: {
      get: function(){
        return this.internalValue/factor
      },
      set: function(val){
        let comp = val*factor
        this.internalValue = comp
        this.value = val
      }
    }
  }
})
#app {
  padding: 20px;
}


h2 {
  font-weight: bold;
  margin-bottom: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>input: </h2>
  <input type="number" v-model="value" step="any"/>
  <h3>
  ext. value: {{value}}
  </h3>
  <h3>
  int. value: {{internalValue}}
  </h3>
</div>

Iโ€™ve added it on JSfiddle here

๐Ÿ‘คevya

0๐Ÿ‘

as @Script47 linked, this answer helped me: How create a v-model modifier to a VueJS Component?

functions in the vue module:

        degToRad(d){
            return d*Math.PI/180;
        },
        radToDeg(r){
            return r/Math.PI*180;
        }

in the html you can break the v-model down to :value and @input, which act similar to getter and setter of the input:

      <div v-for="item in items">
        <input class="val" type="number" @input="item.rotation = degToRad($event.target.value)" :value="radToDeg(item.rotation)" step="any"/>
      </div>
๐Ÿ‘คThomasn

Leave a comment