[Vuejs]-Make two inputs update each other in two-way binding

1๐Ÿ‘

โœ…

I think Iโ€™d use a computed property with get and set.

https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

Iโ€™ve glossed over validation, etc. below but it shows the basic principle of using one data value as the definitive source of truth while the other base uses a computed property.

new Vue({
  el: '#app',
  
  data () {
    return {
      num10: '6'
    }
  },
  
  computed: {
    num2: {
      get () {
        return Number(this.num10).toString(2)
      },
      
      set (num) {
        this.num10 = parseInt(num, 2).toString()
      }
    }
  }
})
<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>

<div id="app">
  <div>
    <label>Base 10 <input v-model="num10"></label>
  </div>
  <div>
    <label>Base 2 <input v-model="num2"></label>
  </div>
</div>
๐Ÿ‘คskirtle

Leave a comment