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

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

Calculating the difference between the old scrolltop and the new scrolltop in jQuery/Javascript

I have a seemingly straightforward question, yet I am struggling to find a solution. Each time a user scrolls, the scrollTop value changes. I want to subtract the previous value from the new value of the scrollTop. However, I am unsure how to store the old ...

Mastering the Art of Displaying Links in Columns within a Table Using ReactJS

I have the following code that fetches data from the backend and displays it in a table. Everything is working correctly. Now, I need to make the first column in the table appear as a link. How can I achieve that? const EditController = () => { c ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

"Using VueJS to allow for easy data editing directly from a table and redirect

I currently have 3 pages set up for my project: 1- The first page is a list displaying all the data in a table format. 2- The second page allows me to add new data (currently using dummy data in the code). 3- The third page is supposed to be an edit page, ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

What is the best approach to modifying array elements using onChange and hooks in React?

I'm struggling to implement something simple, and the solutions I've found so far don't quite address my specific issue. Here's the state in question: const [formFields, setFormFields ] = useState({ formTitle: '', fiel ...

Information gathered from checkboxes and dropdown menus

When gathering information from my form fields, I know how to capture data from input fields using this code: 'formData' : { 'timestamp' : '<?php echo $timestamp;?>', 'token' : '<?php echo md5(&a ...

Replace the value of Undefined with an empty string

I have been utilizing exif.js to extract metadata from the images I upload on a content management system (CMS). However, sometimes when an image does not contain any metadata, certain values may show up as "undefined". My goal is to replace these "undefin ...

Live alerts on the AWS platform (serverless)

Currently, I am working on implementing real-time notifications for my web application in AWS using TypeScript and Vue. The setup involves an RDS instance (mysql), Node.js Lambda functions for the backend, and S3 for the application storage. I am wonderin ...

Changing the image's flex-grow property will take precedence over the flex settings of other child

This is the error code I am encountering, where "text1" seems to be overridden <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!--mobile friendly--> <meta name="view ...

What is the best way to set up playwright-jest so that I can skip a specific Test Suite (spec) file during execution?

In my repository, I have a setup using `playwright-jest` with multiple spec files for test suites. I need to skip one of the spec files without moving it from its current directory in the repo. The default script in `package.json` is `"test": "jest -c jes ...

Struggling to implement a vertical scroll bar in HTML code?

<body ng-app="myApp" ng-controller="myCtrl"> <div ng-show = "dataFromRest" ng-repeat = "x in dataFromRest.posts" > <div class="tittle" style="width: 25%;"> <a href="" ng-click="showDi ...

Tips for customizing the appearance of a Material-ui Autocomplete element

I am facing an issue with my Autocomplete component that is being used in three different places on the same page, each requiring unique styling. How can I dynamically pass styling information from where the Autocomplete is rendered to its component file? ...

Preventing the upload of empty images in an angular application

When selecting multiple images for upload, I sometimes need to make changes or delete the chosen images before actually uploading them. However, if any of the selected images have a size of 0B, I want to stop the upload process for all images, not just the ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Extracting certain elements from a text: a beginner's guide

I am currently developing a task manager that includes a feature to generate a PDF file using jsPDF. I am facing the challenge of extracting specific attributes from a string in order to print them as text utilizing jsPDF. The provided string is: [{" ...