Vue.js: The Pitfalls of the Watch Property

While diving into learning Vuejs, I decided to test out the Watch property during a work break. However, it seems that it's not functioning properly. Can anyone spot what's causing the issue in the code snippet below?

<div id="k2c">
    Kilometers : <input v-model= "Kilometers">
    Meters : <input v-model = "Meters"> 
</div>
<script type="text/javascript"> 
    var vr = new Vue({ 
        el:'#k2c',
        data:{
            Kilometers: 0;
            Meters : 0;
        },

        methods:{

        },
        computed:{
        },
        watch : {
            Kilometers : function(val){   
                this.Kilometers = val;
                this.Meters = val * 1000;  
            },    
            Meters : function(val){
                this.Kilometers = val / 1000;
                this.Meters = val;
            }
        }
    });
</script>

Answer №1

Avoid mutating the properties inside their watchers as it is unnecessary. Additionally, you encountered other issues (refer to comments below).

For more information, check out: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics

<script src="https://unpkg.com/vue"></script>
<div id="k2c">
  Kilometers : <input v-model="Kilometers">
  Meters : <input v-model="Meters">
</div>
<script>
var vr = new Vue({
  el: '#k2c',
  data: {
    Kilometers: 0,          // changed ; to ,
    Meters: 0               // eliminated ; in this line
  },
  methods: {

  },
  computed: {},
  watch: {
    Kilometers: function(val) {
      //this.Kilometers = val;         // commented out this line for removal
      this.Meters = val * 1000;
    },
    Meters: function(val) {
      this.Kilometers = val / 1000;
      //this.Meters = val;             // commented out this line for removal
    }
  }
});
</script>

Note: The two computed properties currently have a cyclic dependency that results in values converging. Be cautious, as this could lead to a stackoverflow error if they diverge.

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

Locating and updating a subdocument within an array in a mongoose schema

Here is the mongoose schema I created: The userId is a unique number that Okta generates for user profiles. var book_listSchema = new mongoose.Schema({ userId:{type: String, required: true}, first_name: { type: String, required: true}, last_name:{ type: ...

Not all dynamic content is loaded through Ajax requests on a single domain

I currently have my domain forwarded (cloaked) to The main page (index.html) utilizes Ajax for loading content. All content loads properly at the original host (moppy.co.uk/wtcdi). However, on the forwarded domain (whatthecatdragged.in), some content fai ...

Getting the search API functioning in react-sortable-tree

My code includes a searchQuery prop as per the API documentation, however, the search functionality does not seem to be working properly. I have found that the API doc lacks clear instructions on how to implement the search feature, and the examples avail ...

In the event that the hash consists of just one string, disregard any additional conditional statements

Currently, I am in the process of updating one of my coding playgrounds and facing some issues. If the user has only the "result" string in the hash like this... testhash.html#d81441bc3488494beef1ff548bbff6c2?result I want to display only the result ( ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

Is the Expand All / Collapse All feature malfunctioning when used with a tree table?

I have been working on implementing the Expand All/Collapse All feature for a nested tree table, but unfortunately, I am not achieving the desired output. I referred to a related question on this topic which can be found here. You can also view the code on ...

How can you ensure the validation of a text box using JavaScript?

Is there a way to confirm that a text box exclusively contains letters, either through JavaScript or regular expressions? ...

Bootstrap Popover not displaying information after an AJAX request

I'm struggling to update the popovers contents with Ajax result in my ASP.Net MVC4 project. Using ASP.Net (MVC4): public ActionResult GetEmployeeDetails(string employeeId) { var contract = UnitOfWork.ContractRepository.ContractBu ...

Utilizing AngularJS for toggling data with ng-click

In my project, I have a unique issue with a list item that toggles a modal and sets a parameter using ng-click. Strangely, when calling a specific function in another location, Course.SelectedCourse returns as undefined, even though Course.ID has a valid ...

Preserving DOM object reference in ASP.Net Ajax PageMethod

When invoking an ASP.Net PageMethod, the call is made like this: function doSomething(htmlElement) { PageMethods.GetText(onSuccess, onFailure); } Is there a recommended approach to keep a reference to the htmlElement in the scenario above, allow ...

Ensuring website responsiveness beyond just the carousel

I found a carousel (inspired by: https://codepen.io/dobladov/pen/kXAXJx) that fetches images from an API. The carousel will switch images as you click on a different image or use the "previous" or "next" buttons. While there are many examples of putting te ...

Discover the location following a designated distance along a direct path connecting two points in the Google Maps API

Using the Google Maps API, I have plotted a straight line from point P1 to point P2. Both points have latitude and longitude coordinates available. I am interested in finding a point (P) along this straight line, located at a specific distance from P1. F ...

Can Stencil.js be utilized to link and include multiple Stencil projects within a single Vue.js Project?

I encountered an issue while attempting to import multiple Stencil.js projects into my Vue project. Following the instructions provided for a single stencil project from this resource: However, when trying to import applyPolyFills and defineCustomElements ...

I am having difficulty accessing the dataset on my flashcard while working with React/Next JS

I'm currently developing a Flashcard app that focuses on English and Japanese vocabulary, including a simple matching game. My goal is to link the two cards using a dataset value in order to determine if they match or not. When I click on a flashcar ...

Attempting to develop a version of Space Invaders utilizing kaboom js on the Replit IDE platform, encountering some difficulties

I'm currently experiencing an issue with changing the scene to the lose state when the player runs out of time or aliens successfully invade. However, I keep encountering this error: Error: scene not found : lose Due to space limitations, I am unabl ...

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...

Drawing glitch on the canvas

Having trouble with drawing an image to a Canvas element and encountering this error: Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1 textureLoadedstaticsprite.js:14 StaticSpritestaticsprite.js:21 (anonymous function) Despite having both th ...

Identifying the initial directory when it is not in English

I've developed a website that supports multiple translated languages, including English, German, Spanish, French, and Italian. Currently, I have a select box on the website that allows users to choose their preferred language. However, I'm facin ...

Tips for restricting access to specific routes in VueJS using Store state

Once a user is authorized, their user type is saved to the state. Based on this type, I need to dynamically show or hide specific routes. src/store/index.js: import Vue from "vue"; import Vuex from "vuex"; import getters from "./getters"; import user from ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...