Issue with Vue @Watch not properly recognizing changes in a boolean value

I'm currently experimenting with watch functions in vue-ts. I have configured a watch function that is supposed to trigger whenever a Boolean variable's value changes, but for some reason, it's not triggering at all and I'm unable to determine the cause.

Here is a snippet of my code:

This is how I declared the data:

<script lang="ts">
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import { CSSModule } from "@/Services/Modules/CSSModule";

@Component({})
export default class CommentCard extends Vue {
  @Prop() comment!: Object;
  @Prop() cmEditor!: Object;
  @Prop() nextCommentDistance!: number;
  @Prop({ default: 300 }) width!: number;
  @Prop() commentIndex!: number;
  private initialHeight: string;
  private textMarker: Object;
  private cssModule: Object;
  private isFocused: boolean;

In the mounted hook, I am updating the data value, expecting the watch function to be triggered:

  mounted() {
    this.setDivHeight();
    this.isFocused = false;
  }

Here is the watch function implementation:

  @Watch("isFocused")
  highlightComment() {
    if (this.textMarker) {
      this.textMarker.clear();
    }
    const css = this.isFocused
      ? "background-color: " +
        this.cssModule.hexToRgba(this.comment.typeColor, 0.5)
      : "background-color: " +
        this.cssModule.hexToRgba(this.comment.typeColor, 0.8) +
        "; box-shadow: 5px 5px 4px rgb(23,24,26)";
    let locations = this.comment.serialize.replace("N", "");
    locations = locations.split(",");
    let startLocation = locations[0].split(":");
    let endLocation = locations[1].split(":");
    this.textMarker = this.cmEditor.markText(
      { line: parseInt(startLocation[0]), ch: parseInt(startLocation[1]) },
      { line: parseInt(endLocation[0]), ch: parseInt(endLocation[1]) },
      {
        css: css,
      }
    );
  }

Despite changing the value of isFocused using a button after mounting, the watch function still does not get called. Any insights on what might be causing this would be greatly appreciated.

Thank you.

Answer №1

To ensure reactivity, make sure to initialize all your properties.

Instead of:

private isFocused: boolean;

Use

private isFocused: boolean = false;

Remember to do this for every property in your Vue application. You can use null as well; just make sure it's not undefined.

For more information, visit: https://v2.vuejs.org/v2/guide/reactivity.html

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

Tips for utilizing method overload in TypeScript with a basic object?

Looking at this code snippet: type Foo = { func(a: string): void; func(b: number, a: string): void; } const f: Foo = { func(b, a) { // ??? } } An error is encountered stating: Type '(b: number, a: string) => void' is not assignabl ...

Utilizing ngModel with an uninitialized object

What is the most effective way to populate an empty instance of a class with values? For example, I have a User Class and need to create a new user. In my component, I initialize an empty User Object "user: User;". The constructor sets some properties, w ...

Enhance autocomplete functionality by incorporating a left icon feature for text fields within the autocomplete component

I have a component with autocomplete functionality that displays tags Autocomplete with tags and I am trying to add a left icon, but only the right icon is functioning correctly. Current Issue When I add a left icon, it shows up but prevents the renderi ...

I'm looking to inject both default static values and dynamic values into React's useForm hook. But I'm running into a TypeScript type error

Below is the useForm code I am using: const { register, handleSubmit, formState: { errors, isSubmitting }, reset, getValues, } = useForm({ defaultValues: { celebUid, //props fanUid, // props price, // props ...

Set a Vue.js variable when the input value changes

Hey there, I'm having trouble with a form that I need to complete using Vue.JS. Basically, I want the value of the 'price_vat' field to update with some calculations every time the 'price_user' input is updated. Everything was work ...

Update the image on a webpage by simply clicking on the current image

Hey there, I'm looking to implement a feature where users can choose an image by clicking on the current image itself. Here's my code snippet. The variable url holds the default image. My goal is to make the current image clickable so that when ...

Steps for retrieving the URL using the getDownloadURL() method

After exploring various options, I have come across multiple solutions but none seem to be suitable for my specific requirements! I have managed to successfully upload a photo to Firebase along with all necessary information. However, when attempting to r ...

Developing a feature that allows users to switch between different sets of information

I'm currently exploring a new project and attempting to design a toggle that switches between monthly and annual payments based on the user's selection, much like the functionality found here: . At present, I have implemented two sets of price c ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

After I deploy my Next.js code to Vercel, including Google Analytics added by @next/third-parties, I am encountering an error that does not appear in development mode

Lately, I completed a next.js project and integrated Google Analytics using @next/third-parties/google. During development, everything worked perfectly, but upon deploying it to vercel.com, an error popped up. ` ./app/layout.tsx:3 ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: The issue arises when setting the div's width as a percentage of the ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Tips on effectively implementing vuedraggable to manage nested components responsible for handling data within nested arrays of data stored in Vuex

I am currently working with a system where I have a collection of items, each of which can contain its own nested list of items that can go to any depth. These items are draggable within the list of object trees and the data is managed using Vuex. The drag ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...

Tips for fixing the error message "Unhandled Promise Rejection: TypeError: response.body.forEach is not a function" in Vue.js 2

Here is how my Vue.js component looks: <script> export default{ name: 'CategoryBsSelect', template: '\ <select class="form-control" v-model="selected" required>\ <option v-for="option in opt ...

Transitioning from Vuetify 2 to Vuetify 3: Handling v-list-item-icon with v-if Conditionals

I have streamlined this post to focus solely on v-list-item-icon; if that's what you're here for, scroll down for the answer. A commenter suggested splitting my migration questions into separate posts. I've followed that advice and created ...

I am confused about the term "can only be default-imported using the 'esModuleInterop' flag", could you explain it to me?

I ran into a puzzling error: lib/app.ts:1:8 - error TS1259: Module '"mongoose-sequence"' can only be default-imported using the 'esModuleInterop' flag and it seems to be related to this line of code: import _ from 'mongoose-sequ ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...

A guide to implementing typescript with Next.js getStaticProps

I have Next.js set up with the TypeScript feature enabled Currently, I am attempting to utilize the getStaticProps function following the guidelines outlined here: https://nextjs.org/docs/basic-features/typescript Utilizing the GetStaticProps type export ...