0

I am building a tool to calculate how much it would cost to buy certain material. The problem is that sometimes the user buys it either by mass or volume.

I would like a way to have two active inputs (mass and volume) and each automatically updates considering the material density.

I tried computed properties and watchers but couldn't make it work properly.

Here is what I'd like it to look like and what I tried https://jsfiddle.net/yfuk958j/

  Mass = <input v-model.number="mass"> <br/> 
  Volume = <input v-model.number="volume"><br/>
  computed: {
    volume() {
      return this.mass * this.density
    },
    mass () { 
    return this.volume / this.density 
    }
   }

1 Answer 1

1

All you need is 2 inputs, each bound to a property of your vm. And a watch function to update any of them when the other changes:

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  data: {
    density: 1,
    mass: 1, 
    volume: 1,
    inputType: 'mass'
  },
  watch: {
    mass(val) {
      this.volume = val/this.density;
    },
    volume(val) {
      this.mass = val*this.density;
    },
    density(val) {
      this.volume = this.mass/val;
    }
  },
  methods: {
    round(val) {
      return Math.round(val * 1e3)/1e3
    }
  }
})
span {min-width: 100px; display: inline-block;}
input[type="range"] {width: 200px;}
input[type="number"] {width: 100px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>
    <span>Density:</span> <input v-model="density" type="range" min=".1" max="10" step="0.1">{{density}}g/cm<sup>3</sup>
  </div>
  <div>
    <div>
      <span>Mass:</span> <input v-model="mass" type="range" min="1" max="1e4" step="0.001">
      <input v-model="mass" type="number" min="1" step="0.1" max="1e4">g
      [Volume: {{round(volume)}}cm<sup>3</sup>]
    </div>
    <div>
      <span>Volume:</span> <input v-model="volume"  type="range" min="2" max="1e4" step="0.001">
      <input v-model="volume"  type="number" min="2" max="1e4" step="0.1">cm<sup>3</sup>
      [Mass: {{round(mass)}}g]
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.