What is the best way to monitor multiple properties within a Vue component?

I'm facing a challenge in updating the Vue component property, station, whenever certain other properties are updated. Since computed properties are synchronous and this task involves an API request, I couldn't make it work as a computed property.

After reading an insightful response on Vue core issues, I came across the documentation for using vm.$watch. It seems like this is what I need, but I'm struggling to implement it correctly within the context of this component.

I believe I should be using this instead of vm as mentioned in the docs, but when I try using this on the left side of the arrow function that serves as the first parameter of $watch, I encounter errors like

Invalid left-hand side in arrow function parameters
.

The section where I use vm.$watch can be found towards the end of the code snippet for this component. The recurring error that I'm getting is:

Failed watching path: "[object Object]" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.
(But isn't that what I'm doing...?)

<template lang="html">
  <div>
    {{ station }}
  </div>
</template>

<script>
import ApiService from '@/services/ApiService';

export default {
  name: 'Chart',
  props: {
    mode: String,
    toDate: String,
    toTime: String
  },
  data() {
    return {
      stationId: 3069,
      station: {}
    };
  },
  watch: {
    station: function() {
      // Render function
    }
  },
  methods: {
    getInfo: async function(opts) {
      const stationData = await ApiService[this.mode]({
        id: opts.id,
        toTime: `${opts.toDate}T${opts.toTime}`,
        fromTime: `${opts.fromDate}T${opts.fromTime}`
      })
        .then(res => {
          return res.data.station.properties;
        })
        .catch(err => {
          console.error(err);
          return {};
        });

      return stationData;
    }
  },
  created: function() {
    // MY WATCHING STARTS HERE  
    this.$watch(
      () => return {
        mode: this.mode,
        stationId: this.stationId,
        toDate: this.toDate,
        toTime: this.toTime
      },
      async function(data) {
        this.station = await this.getInfo({
          mode: data.mode,
          id: data.stationId,
          toDate: data.toDate,
          toTime: data.toTime
        }).then(res => {
          return res;
        });
      }
    );
  }
};
</script>

Answer №1

Your observer is coming back in an arrow function. It should look like this:

this.$watch(
  () => {
     return {
       mode: this.mode,
       stationId: this.stationId,
       toDate: this.toDate,
       toTime: this.toTime
     }
  },

It is incorrect to use the code like this:

() => return { 

An arrow function will automatically return the value if there are no curly braces, so you can also write it like this:

this.$watch(
  () => ({
     mode: this.mode,
     stationId: this.stationId,
     toDate: this.toDate,
     toTime: this.toTime
  }),

Note that parentheses are used for returning an object. For more information, you can refer to this post.

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

Detecting a Checkbox Click Event in JavaScript

I am working with a table that has the following structure: <tbody id="ggwp"> <tr class="r123 disable-it"> <td> <input type="checkbox" name="item" class="row" statusid="1234"> </td> </ ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

The zoom level on Google Maps adjusts based on the size of the window when it

In reference to my previous inquiry about Google maps responsive resize, I am now looking to incorporate dynamic zoom levels based on the window size. Specifically, I want the map to automatically adjust its zoom level when the browser window is resized -- ...

The $http service encounters an error while attempting to retrieve a JSON file from the server

When attempting to fetch a file from the server, I utilize the $http service in the following manner: $http({url: url, method: "GET", withCredentials: true}); For some mysterious reason, an exception is only thrown when trying to retrieve JSON files from ...

jQuery Ajax Pagination - The first page and the selected one function correctly, but the rest do not

Allow me to provide a more detailed description of my issue than what is indicated in the title... I am utilizing CodeIgniter pagination (adjusted to accommodate Bootstrap's requirements), and have set it up to display my links as follows: <div cl ...

Creating a personalized animation user interface for an ExtJS message box is a great way to enhance

I want to display a customized message box in extjs with a unique user interface. I have experimented with Ext.MessageBox.show and Ext.Msg.wait functions for this task. My specific requirement is to exhibit a custom "Loading" image instead of a static rect ...

Rotating Images from an Amazon S3 Bucket within a React Application

My app allows users to take photos and store them in an AWS S3 bucket. The URL for each image is saved so that it can be viewed later. Oddly, when viewing the image directly in the S3 bucket, it appears correctly oriented. However, when accessed via the ap ...

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

Vue-good-table does not show the "empty state" once it has been populated with data

I am facing an issue with my vue-good-table where it does not re-render to display the "emptystate" message when I set the rows field to an empty array. Initially, it shows the message before I assign values into the rows field and then correctly displays ...

Using ESM imports in webpack configuration

I'm in the process of creating a webpack application and I am keen on utilizing ESM (ECMAScript Modules) throughout the entire project. This involves configuring the webpack.config file to allow for ESM imports. Previously, I knew that this could be ...

Easily visualize the JSON object hierarchy within Eclipse using JavaScript

Is there a way to view the JSON parse objects structure in Eclipse without using console.log() in Chrome due to cross domain issues? I need assistance with how to view the [object Object] returned structure from Json.Parse. ...

Bi-weekly Calendar Gathering

I am able to get my events sorted by day with the following code: daysOfWeek: [2], However, I have not been able to find any information in the documentation on how to make it sort fortnightly. Can this be done with fullcalendar? Solution: Just a heads ...

What is the best way to incorporate the parallax effect into a v-carousel?

Currently, I have a "v-carousel" containing multiple images and now I am looking to incorporate a parallax effect into it, similar to "v-parallax". <v-carousel cycle height="600" hide-delimiter-background show-arrows-on-hover> <v-carousel-i ...

Acquire information from database in Laravel 9 with the implementation of Vue js 3

My goal was to retrieve data from the database and showcase it within the app. This is how I implemented it : <h2 class="lowongan1" v-for="value in list_lowongan"> {{ value.title }}</h2> <p class="descJob1" v ...

IE page refresh causing jQuery blur to malfunction

Our website features a textbox with a watermark that appears and disappears based on focus and blur events in jQuery. However, we have encountered a unique issue with Internet Explorer browsers. Whenever a user clicks on the textbox, the watermark disapp ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

"Input numbers into the box provided to calculate the total sum

I have a problem with my code that involves prompting the user to input two numbers and then adding them together. However, when I run the code, it concatenates the numbers as strings rather than performing addition. Here is the code snippet in question: ...

Placing v-navigation-drawer below v-app-bar in Vuetify: a step-by-step guide

I came across the documentation on https://vuetifyjs.com/en/components/application/#application-components which mentions that v-navigation-drawer can be set to appear below the v-app-bar rather than beside it, but unfortunately it doesn't provide cle ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...