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

Retrieving information from MongoDB and Electron JS through IPC renderer

programming file this.$electron.ipcRenderer.send('get-result') this.$electron.ipcRenderer.on('got-it', (event, data) => { if (data.status) { this.allResult = data.result } else{ thi ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...

How come TypeScript does not generate an error when attempting to import a default export that does not exist?

As I work on converting my code from non-TypeScript CommonJS files to TypeScript ES6 modules, I encountered an issue with the import statements. Specifically, I needed to use import * as x instead of import x: The original snippet looked like this: const ...

Error: When trying to run the `ng build` command in Git Bash, TypeScript module cannot be

When attempting to execute ng build using Git Bash, I encountered this error message, even though I had previously executed npm install -g typescript. Where should I place the typescript installation so that Git can detect it? Error $ npm install -g typ ...

Automatically divide the interface into essential components and additional features

Consider the following interfaces: interface ButtonProps { text: string; } interface DescriptiveButtonProps extends ButtonProps { visible: boolean, description: string; } Now, let's say we want to render a DescriptiveButton that utilize ...

Leverage the VTTCue Object in an Angular2 project using Typescript

I am looking to dynamically load subtitles onto a video. let subs:TextTrack = video.addTextTrack('subtitles'); for (let dataSrt of dataSrts) { let cue: any = new VTTCue( dataSrt['startTime'], da ...

Determine the time difference between the beginning and ending times using TypeScript

Is there a way to calculate the difference between the start time and end time using the date pipe in Angular? this.startTime=this.datePipe.transform(new Date(), 'hh:mm'); this.endTime=this.datePipe.transform(new Date(), 'hh:mm'); The ...

What seems to be causing the malfunction in my child component's functionality?

When passing data to child components using props, sometimes it may seem like the tag isn't working properly. For example, in this case, why isn't 'hello' being printed out? Here is the code snippet: <div id="app"> <child m ...

Using Tailwind classes in Vue props

Looking to utilize a Vue prop within a Tailwind CSS class. The class in question is bg-[url('address')] (which sets the background image), with 'address' being the prop. Despite various attempts, I keep encountering the following erro ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...

Invoke the dispatch function from React-Redux in a stateless component with the help of a wrapper

I have a React-Redux store that is wrapped in a next-redux-wrapper. I am facing an issue where I cannot dispatch a function outside of a react component due to the wrapper. Is there a way to import the store and use dispatch while still using the wrapper? ...

What is the reason behind useEffect giving warnings for unnecessary fields that are not included in the dependencies array?

After reviewing the documentation for useEffect, I am puzzled by the warnings I receive for every variable and function used within useEffect, despite not having a dependency on them. Take a look at my useEffect below: const [updatedComm, setUpdatedComm] ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

Utilizing Vue.js 2 to dynamically update data through directives

Is it possible to change a data property from a directive using single file components? For instance, consider the following code... export default { name: 'app', data: function() { return { is_loading: true ...

Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes. Each row has been formatted with a newline at the end of the code. formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n' The da ...

What causes the Vue JS this.$listeners to be undefined?

Vue.js version: 2.4.2 The issue with the following component is that it always shows this.$listeners as undefined. module.exports = { template: `<h1>My Component</h1>`, mounted() { alert(this.$listeners); } } After regis ...

Looking for guidance on creating a TypeScript interface within React?

How can I properly declare the tagItems in the following code? I am currently getting a warning in VSCode that reads: (property) tagItems: [{ id: number; label: String; name: String; state: Boolean; }] Type '[{ id: number; label: stri ...

Tips for preventing issues with Javascript latency causing flash out during page loading in Chrome

When building a page with Vue.js or any other Javascript, the issue of temporary flash during loading on Chrome due to constructing latency can be quite frustrating. This delay is not caused by asynchronous ajax requests, but rather the processing involv ...

Direct user to an external webpage with Vue 3

I created a navigation bar with links to external social media platforms. After clicking on the GitHub link, I encountered some errors and here are the URLs for reference: https://i.sstatic.net/KCh3C.png https://i.sstatic.net/OXQOK.png <template> ...

A guide on integrating CKEditor's simple upload adapter and resolving the CKEditor error in Vue.js: CKEditorError - duplicated modules

Looking to enhance my Vue project with CKEditor functionality, I successfully integrated the editor but now wish to enable image uploads within the text area. Despite using the simple upload adapter as outlined below, the page displaying the editor is no ...