connect the input to a factor using v-model

I currently have a value that I need the user to adjust. Here's my current setup:

<input type="number" v-model="value" step="any"/>

However, the internal value is in radians while I want the user to see and input a degree value.

So, I want the displayed value (in degrees) to be synchronized bi-directionally with the internal value (in radians) using a multiplication factor. How can I achieve this in Vue.js?

In C#, I would accomplish something like this:

float internalValue;
float factor = 3.141/360;
float externalValue {get {return internalValue/factor} set {internalValue=value*factor}};

Is there a similar approach in JavaScript that will work seamlessly with the v-model binding?

Answer №1

Consider implementing a Computed property using get/set functionality, as outlined in the VueJS documentation.

Here is an example:

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>

You can also access it on JSfiddle here

Answer №2

After reading the response shared by @Script47, I found this answer particularly helpful: How can I create a v-model modifier for a VueJS Component?

The vue module includes the following functions:

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

You can segment the v-model into :value and @input in the HTML, performing similar actions to getter and setter of an input field:

      <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>

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

Preventing duplication of code execution in recycled PHP elements

Currently, I have implemented a generic toolbar that is used on multiple pages of my web application by using PHP include. This toolbar contains log in/log out functionality and checks the log in status upon loading to update its UI accordingly. Initially ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

What could be causing this JavaScript if statement to consistently evaluate to true?

I'm facing an issue where I want to run a specific block of code when a div is clicked for the first time, and then another block when it's clicked for the second time. The problem is that even though my alert shows the variable being updated wit ...

Having difficulty loading the JSON configuration file with nconf

I'm currently attempting to utilize nconf for loading a configuration json file following the example provided at: https://www.npmjs.com/package/nconf My objective is to fetch the configuration values from the json file using nconf, however, I am enc ...

Having trouble with the jQuery select2 AJAX functionality?

I've been experimenting with the jQuery select2 plugin and attempting to integrate AJAX with my external data, but unfortunately it's not working as expected. I'm curious if anyone can help me identify what mistake I might be making or if th ...

unexpected issue when trying to append a child element after creating its innerHTML

Upon executing this script, I expect to see the initially empty div with id="checkboxes" transformed into: <div id="checkboxes"> <label><input type="checkbox">option1</label> <label><input type="checkbox">opt ...

res.send() triggers an error of TypeError: Attempting to convert circular structure to JSON

I've encountered an error message that has been discussed before, but none of the proposed solutions seem to work for my situation. My current project involves building a backend express server to manage API requests for a React application. I have c ...

Ways to conceal a button using Javascript

Due to my limited JavaScript experience, I am struggling with understanding the event flow. This was written in haste, and further editing may be needed. I am working on creating a stack of cards (Bootstrap cards) along with a load button. To keep it inde ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...

Insert a 5-second delay in the JavaScript code before triggering the click event on the next button

Currently, I have a JavaScript code in place that is fairly straightforward. The webpage contains about 100 buttons with the class button, and I am successfully simulating clicking each one of them systematically. However, I would like to introduce a dela ...

Is there a way to retrieve the request object within loopback operational hooks?

I am currently utilizing loopback 3.x and have created an Access Hook within my code. My goal is to include a condition based on the User Agent. Specifically, I am looking to access Request > Headers > User-Agent. Is it feasible to retrieve this in ...

Challenges encountered with input outcomes

I am facing an issue with input results. I have a button that triggers a function to check for empty input fields. However, when I click the button, it always falls into the last if statement and displays as if the fields are not empty. I have already att ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

When using NextJS with Redux Persist, the HTML does not get rendered in the initial server

I am currently utilizing ReactJS/NextJS along with Redux and redux-persist, as well as Ant Design. Recently, I have noticed that my html codes and other data are not rendering in the page's source. They do render in the browser and when inspected, but ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

What is the approach for utilizing Vue List Rendering with v-if to verify the presence of items within an array?

My current implementation utilizes v-if to conditionally display a list of cafes. However, I am interested in filtering the list based on whether a specific drink item is found in an array. For instance, I have a collection of cafes and I only want to dis ...

Issue with Vuex getter not reflecting correct value after modifying an array

I've been delving into the world of vuex, and I'm currently working on fetching the count or an array when I make additions or removals. Below, you'll find the code snippets I'm working with. home.vue template <template> < ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...