Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume.

My goal is to have two active input fields (one for mass and one for volume) that automatically update based on the material density.

I attempted using computed properties and watchers, but couldn't achieve the desired functionality.

Here is the ideal layout I envision and what I've tried so far: 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 
  }
}

Answer №1

To make this work, you just need two inputs that are connected to properties in your vm. You also need a watch function to update one input 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic Node.js server constantly updating

My goal is to create a dynamic Node.js Express server that updates live, possibly by creating a specific route like /update to load a new configuration file. My concern is that the server could be in any state when the update occurs. It's possible tha ...

What sets apart !$scope.variableName from $scope.variableName in AngularJS?

Greetings to all my fellow coders! As a newcomer in the field, I often find myself pondering over things like this. Would someone be kind enough to elucidate the dissimilarity between these two elements in AngularJs? $scope.variableName and !$scope.var ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

What is the best way to eliminate an item from an array in JavaScript or AngularJS?

I'm attempting to eliminate objects from an array and retrieve the resulting array. I've been using a remove function, but it's not functioning as expected. Here is the input I'm working with: The goal is to remove all values in the ar ...

Storing Array Data in Angular $scope (Javascript)

I am currently altering the Altair Material Design Template and incorporating an Angular JS controller. After successfully calling an API and creating variables in a for loop, I intend to write them to $scope.dragulaItems. While this process seems to work ...

WordPress CSS & JS files failing to enqueue properly

My attempt to integrate my CSS and JS files with WordPress has not been successful. Although my CSS works through the Custom CSS tab, this is not an ideal solution. Below is the code from my functions.php file for your reference. Can you help me troublesho ...

Dynamic Vue/Vuex component remains stagnant

In my Vuex store, I have a collection of "nodes" where each node is categorized as either an Accordion or a Block. { "1":{ "id":1, "title":"Default title", "nodes":[], "type":"Block" }, "2":{ "id":2, "title":"Default title", ...

Establish a connection to a regular socket by utilizing WebSocket technology

I am attempting to connect a client interface to a hardware device using WebSocket in a browser like Chrome. The code snippet I have been using for connection is as follows: var ws = new WebSocket("ws://127.0.0.1:13854"); ws.onopen = function() ... Howev ...

AngularJS tree grid component with customizable cell templates

I have been utilizing the tree-grid component in AngularJS from this link: Here is an example of it on Plunker: http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview In comparison to ng-grid, I am unable to define cellTemplate, but I do require the abilit ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...

The animation of a cube rotating to a different face is not functioning properly when using three.js

Why is my cube not animating when rotating to another face with the code below? How can I resolve this issue? new Vue({ el: '#app', data () { return { camera: null, scene: null, renderer: null, mesh: null, ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Guide on how to store a CSS image in a server using PHP

Looking to create a button generator using JavaScript on my website, similar to the one found here http://css-tricks.com/examples/ButtonMaker/. In addition to generating buttons, I also want to include a save button so that users can save the button image ...

Angular 4 is unable to attach to 'formGroup' as it is not recognized as a valid property of 'form'

As a beginner with Angular 4, I decided to explore model driven forms in Angular 4. However, I keep encountering this frustrating error. Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form ...

Unable to grab hold of specific child element within parent DOM element

Important Note: Due to the complexity of the issue, the code has been abstracted for better readability Consider a parent component structure like this: <child-component></child-component> <button (click)="doSomeClick()"> Do Some Click ...

What is the best way to enclose a block of content with <div> and </div> tags using the append() function?

My goal is to add an outer div container by first appending it, then adding content, and finally appending the closing tag. However, I'm encountering an issue where the div I added at the beginning automatically closes itself, resulting in two separat ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...