I found myself in a bit of a predicament as I tried to transition a petite

Recently, I've been working on a small project that is built using pure HTML, CSS, and JavaScript. As I am delving into the realm of Vue.js, I decided to challenge myself by migrating this project to Vue.js.

Here is how it currently functions with JavaScript:

const toKelvin = {
  Celsius: (t) => t + 273.15,
  Farenheit: (t) => (t + 459.67) / 1.8,
  Rankine: (t) => t / 1.8,
  Rømer: (t) => ((t - 7.5) * 40) / 21 + 273.15,
  Newton: (t) => (t * 100) / 33 + 273.15,
  Delisle: (t) => 373.15 - (t * 2) / 3,
  Reaumur: (t) => t * 1.25 + 273.15,
  Kelvin: (t) => t
};

decimalTemp.addEventListener("input", decimalTempEvent);

// Remaining JavaScript functionality

// HTML structure goes here

(HTML Structure)

As I began the migration process to Vue, I found myself grappling with whether certain functions should belong in methods or watch.

I initially placed the eventListener call in the HTML using @input, but considered using @change instead.

Below is an overview of my progress so far:

<template>

(Vue template code)

</template>

<script>
export default {

(Vue script logic)

</script>

<style scoped>
(CSS styling)
</style>

Answer №1

You have the option to substitute watch and data with computed, which essentially combines both functionalities into one. By default, computed only has a getter, but you can also include a setter.

I've enhanced your code for better efficiency. Essentially, you only require the base unit (let's say Kelvin), and then perform operations based on this unit while adjusting other units whenever any change is made.

Here is the functional code (snippet on codesandbox.io):

<template>
  <div id="temperatureList">
    <label for="decimalTemp">Decimal Places </label>
    <input
      class="decimals"
      type="number"
      min="0"
      max="10"
      step="1"
      v-model="decimalTemp"
    />
    <table>
      <tr>
        <td>
          <input
            id="kelvinIn"
            type="number"
            min="0"
            step="1"
            v-model="Kelvin"
          />
        </td>
        <td>Kelvin (K)</td>
      </tr>
      <tr>
        <td><input id="celsiusIn" type="number" v-model="Celsius" /></td>
        <td><label for="celsiusIn">Celsius (ºC)</label></td>
      </tr>
      <tr>
        <td><input id="farenheitIn" type="number" v-model="Fahrenheit" /></td>
        <td><label for="farenheitIn">Farenheit (ºF)</label></td>
      </tr>
      <tr>
        <td><input id="newtonIn" type="number" v-model="Newton" /></td>
        <td><label for="newtonIn">Newton (ºN)</label></td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  name: "Temperature",
  data: () => ({
    decimalTemp: 0,
    baseInKelvins: 293.15,
  }),
  computed: {
    Kelvin: {
      get: function () {
        return this.baseInKelvins.toFixed(this.decimalTemp);
      },
      set: function (newVal) {
        this.baseInKelvins = +newVal;
      },
    },
    Celsius: {
      get: function () {
        return this.fromKelvin()
          .Celsius(this.baseInKelvins)
          .toFixed(this.decimalTemp);
      },
      set: function (newVal) {
        this.baseInKelvins = this.toKelvin().Celsius(+newVal);
      },
    },
    Fahrenheit: {
      get: function () {
        return this.fromKelvin()
          .Fahrenheit(this.baseInKelvins)
          .toFixed(this.decimalTemp);
      },
      set: function (newVal) {
        this.baseInKelvins = this.toKelvin().Fahrenheit(+newVal);
      },
    },
    Newton: {
      get: function () {
        return this.fromKelvin()
          .Newton(this.baseInKelvins)
          .toFixed(this.decimalTemp);
      },
      set: function (newVal) {
        this.baseInKelvins = this.toKelvin().Newton(+newVal);
      },
    },
  },
  methods: {
    fromKelvin: () => ({
      Celsius: (t) => t - 273.15,
      Fahrenheit: (t) => 1.8 * t - 459.67,
      Newton: (t) => ((t - 273.15) * 33) / 100
    }),
    toKelvin: () => ({
      Celsius: (t) => t + 273.15,
      Fahrenheit: (t) => (t + 459.67) / 1.8,
      Newton: (t) => (t * 100) / 33 + 273.15
    }),
  },
};
</script>

<style scoped>
table {
  margin: 0 auto;
}
table tr td {
  text-align: left;
}
input {
  text-align: right;
}
</style>

Answer №2

Your query may not have been crystal clear in your previous message, so I'll make an attempt to address the concerns and uncertainties you expressed.

I was unsure about whether functions should be placed in methods or in watch.

Functions that are called from the template should be housed within the methods property, unlike computed properties which don't take parameters and are expected to only return a "computed" value.

The watch property is designed to contain functions that "listen" for changes (such as in props, route params, etc.), triggering each time there's a change in these values.

I included the eventListener call in the HTML using @input, but I'm uncertain if it would be more appropriate to use @change.

The distinction between @input and @change lies in the fact that @input triggers with each keystroke, while @change triggers upon submission (or pressing enter if not within a form and no submit button is associated with that input).

Ultimately, the choice depends on the desired outcome, performance considerations, and personal preference.

If you're not fetching substantial data from an API every time the input value (linked through v-model) changes, then @input may be the preferred option. Even if you are retrieving a lot of data, utilizing a "debounce" method can help fetch the data after a certain delay to prevent excessive requests.

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

Built-in Promises within MongoDB

Is there a way to determine which methods in mongoDb have an inbuilt promise? For example, "updateOne() , findOne()" have inbuilt promises that we can access using ".then", but many other mongoDB methods lack this feature. How can we identify which methods ...

There are no specified operations outlined in the Node.js Express documentation

swagger ui https://i.stack.imgur.com/UIavC.png I've been struggling to resolve this issue where the /swagger endpoint seems to only partially read the swagger.json file. Despite configuring everything correctly, no errors are appearing. It simply dis ...

Create a jQuery URL within the $.ajax function

Attempting to execute a $.ajax call and send data to a php file. The php file is situated in a component's directory, while the js file is located in the webroot directory. How can the url section of the $.ajax be configured correctly to point to the ...

Hover over a DOM element to highlight it, similar to the functionality of the inspect tool

Our website features a bookmarklet that triggers an inspect-like highlighter when a user clicks a button. We are aiming for this functionality to be compatible across different browsers. To achieve this, we must be able to detect the DOM element during mo ...

Inspect the json data to find a specific value and then determine the corresponding key associated with

I am currently working with JSON data retrieved from which I am storing in a variable. Despite my limited experience with JSON/JS, I have been unable to find a solution through online searches. Here is the code snippet: function checkMojang() { var moj ...

The CSS for a VueJS compiled app seems to fail to apply properly unless manually copied and pasted into the browser's style editor

After compiling my vuejs app with npm run build, I noticed that the CSS does not display when viewing it in Firefox. Surprisingly, the styles do load in the network tab and appear under the style editor, but with "0 rules". However, everything displays fin ...

What could be causing the defaultOpenKeys in my ant design to malfunction?

Using the Ant Design library, I have implemented a Menu/Submenu feature. Additionally, I created a custom function component called CustomSubMenu. This component simply displays the Ant SubMenu and is used within a wrapper component Menu. However, I am enc ...

Selecting the next element in the DOM using Javascript

Here is the structure of my current setup: <div class="wrapper"> <div class="first"> <a class="button" href="">click</a> </div> <div class="second"> <div class="third"> S ...

Utilize FCM Firebase in Node.js Express to efficiently send out mass push notifications

In my app's admin panel, there is a feature that allows the admin to send push notifications to all users using REST API. The FCM tokens are retrieved from the database. After checking out the Firebase documentation here, I found out that only up to ...

Encrypt JavaScript for a jade layout

I need to find a way to successfully pass a .js file to a jade template in order for it to display correctly within an ACE editor. However, I am encountering errors when attempting to render certain files that may contain regex and escaped characters. How ...

What is the most efficient approach to save a value for future utilization in a subsequent function? I've heard that exploiting global variables is highly unfavorable

So I have this code that can be found at http://jsfiddle.net/8j947/10/. It returns either true or false for the variable isLive. My main concern now is how to utilize the variable onLive in a subsequent function. While I've encountered some solutions ...

What are the steps to implementing AJAX pagination without utilizing a database?

Is it possible to implement AJAX pagination without relying on MySQL? Can I create a PHP file containing the text and markup needed for display, and by clicking on page numbers, serve that content to the user? Can this be achieved using only jQuery and PHP ...

Error 14 is occurring when attempting to use string values for the categories on the Highcharts

Starting right away, here's the requested chart using ChartJS. We have two x-axes. One displays power from a meter and the other displays meter state over time (open, closed, or in standby). Both datasets use Unix time on the X axis. The Y axis for po ...

Combining Angular variables within HTML tags: A Guide to AngularJS

As a newcomer to AngularJS, I am truly impressed by its capabilities. One thing I am eager to learn is how to include an AngularJS binding within an HTML attribute, while also adding another string to it. I often use unique names like "thisform" and "thisd ...

Display a specific number of page indicators on the Flickity plugin

Currently, I am utilizing the flickity plugin to create a slideshow feature on my website. My goal is to display navigation dots on the images to facilitate user interaction. If you are interested, you can access the plugin through this link: I would lik ...

Having trouble setting a value for a textbox in angularjs

Greetings! I am currently working on a web application using AngularJS. My task involves binding data from various API's to a textbox in my project. Below is the snippet of the HTML code where I attempt to achieve this: <input class="with-icon" ty ...

Submitting an extremely large string to an Express server using JS

How can a large String be efficiently sent to a Node.js Express server? On my webpage, I am using Codemirror to load files from an Express server into the editor. However, what is the most effective method for sending "the file" (which is actually a bi ...

Incorporate a linked select dropdown into the registration form

I am working on a sign-up form and trying to integrate 2 linked select boxes into the form. The code for the linked select boxes works fine separately but when I attempt to add it to the form, it doesn't display as expected. I attempted to incorporate ...

The dirtyVertices feature in Three.js seems to be malfunctioning

In my three.js project, I created a 12*12 plane and attempted to modify its vertices between two renderings without success. Despite adding the following code, no changes were observed: ground.geometry.dynamic = true; ground.geometry.__dirtyVertices = tr ...

Tips for nesting maps in React without causing redundant renders

I have a list of all the items in the array let products = [ { name: "iPhone 12", storage: "64GB" }, { name: "iPhone 12 Pro", storage: "256GB" }, { name: "iPhone 12 Pro Max", storage: "512GB" ...