unable to retrieve data variables within Vue.js watch handler

I am attempting to assign a data variable within a watch handler function for an input field in a VueJs Component. The code snippet is as follows:

data() {
    return {
        params: {
            // default params to 1 month
            from: new Date().setMonth(new Date().getMonth() - 1),
            to: Date.now(),
            skip: 0,
            limit: 100
        }
    }
}
watch: {
    dates: { 
        handler: date => {
            console.log(this.params)
            if (date.start) {
                this.params.from = moment(date.start, "YYYY/MM/DD")
            }
            if (date.end) {
                this.params.to = moment(date.end, "YYYY/MM/DD")
            }
        },
        deep: true
    }
}

Upon setting an input for the dates variable in the view template, I encounter an undefined result for this.params in the console log, and face an error when trying to set this.params.from. Consequently, I attempted accessing it through a method:

methods: {
    printParams() {
        console.log(this.params)
    }
}

By invoking it within the view template, the params object is correctly resolved.

Is there something crucial that I am overlooking here?

Answer №1

To prevent any further binding issues, it is advised to refrain from utilizing the arrow function syntax in this situation. Instead, opt for ES6 Object shorthands:

watch: {
    dates: { 
        handler(date) {
            console.log(this.params)
            if (date.start) {
                this.params.from = moment(date.start, "YYYY/MM/DD")
            }
            if (date.end) {
                this.params.to = moment(date.end, "YYYY/MM/DD")
            }
        },
        deep: true
    }
}

By doing so, this will automatically be bound to the appropriate context.

Answer №2

Why not experiment with binding this to your event handler?

        handleDate(date) {
            console.log(this.params)
            if (date.start) {
                this.params.from = moment(date.start, "YYYY/MM/DD")
            }
            if (date.end) {
                this.params.to = moment(date.end, "YYYY/MM/DD")
            }
        }.bind(this)

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

Exploring the dynamics of Kendo UI's MVVM approach using J

Is there a way to make an ajax call in Kendo without involving the grid? I am new to Kendo and struggling to populate a span element with data fetched from one of my controller methods. The data is present as I can see it in the alert message, but it' ...

Periodically transmit information to a Google Script web application

I am currently working on a Google Script web app to automatically update data from a Google Sheet every 30 minutes. I initially attempted using the page refresh method, but encountered an issue where the web app would display a blank page upon refreshin ...

jwt.verify is failing to throw errors when handling expired tokens

Currently utilizing JWT (jsonwebtokens) in my Node.js project. While generating a token, I aim to trigger an error when the token reaches its expiry. The process involves successful creation of the token which is then validated for expiration within the m ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

When I incorporate the "a" tag, transformations take place within my divs

My divs undergo changes when I use the "a" tag. Despite writing 600 lines of code, my website is starting to malfunction. It was not supposed to have any impact when I used the "a" tag. Note: I never assigned a class to it. Here is an example: <a hre ...

Troubleshooting HTML/CSS and JavaScript Issues with Dropdown Menus

I'm having trouble getting my dropdown menu to work properly and I can't figure out why. The JavaScript code should toggle a class that hides the language options and slides up the other tabs like "Contact". However, when I click the button, noth ...

What is the best way to transform a list of Python+Flask objects into a list of JavaScript objects?

Here's a Flask application that showcases a list of objects. from flask import * app = Flask(__name__) class Entry: def __init__(self, name, surname): self.name = name self.surname = surname entries = [] entries.append(Entr ...

Does it violate best practices to employ a concealed <input> element with a predefined value in PHP for subsequent transmission to jQuery?

I am currently working on a custom WordPress theme that includes a contact form with error-checking capabilities using jQuery. After successfully sending an email, I want to display a confirmation message accompanied by a loading.gif to indicate activity. ...

Malfunctioning Vue.js with Typescript

After completing the 'npm install -g vue' (v2.6.10) step and removing strict-ssl from the configuration file, I am consistently facing an issue where typescript@^3.4.5 is being reported as corrupted. This problem has been replicated on multiple v ...

Guide on manipulating props in VueJS

Building an application using Vue2 involves passing data from a parent component to a child component through v-for. Here's how the parent component looks: <template> <div class="row" v-for="(item, index) in variables" ...

Generating a tree structure using a JavaScript array

Looking to build a tree structure from a given list of data where the paths are represented like: A-->B-->C-->D-->E.. A-->B-->C-->D-->F.. A-->F-->C-->D-->E.. . . . All possible data paths are stored in an array. The de ...

How to use JavaScript to validate if an input field is empty in IE

I am facing an issue with the required attribute in IE9. While the attribute works fine in IE10 and above, I am struggling to get it to function in IE9. I have attempted the following: $('#submit-button').click(function(){ if($('#message ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...

Sending JavaScript functions to PHP files via Ajax

My Current Project: I am currently developing a script that provides users with choices and generates new options based on their selections. To achieve this, I have created two scripts - one for the HTML structure of my page and another for fetching serve ...

Providing external data to directives within AngularJS

When creating directives, it's recommended to keep the data/model separate from the directive itself. For instance, let's say we have a directive called "Event" like this: <div class="event"> <h1>{event.title}</h1> < ...

Using JavaScript to insert specific values into an array of floats

let floats = [6, 10, 10, 10, 20, 48, 50.5, 60, 60, 78, 90]; let evens = [{}]; for(let i = 0; i < floats.length; i++){ if(floats[i] == floats[i - 1]) { evens[evens.length - 1][i - 1] = floats[i - 1], evens[evens.l ...

Is it possible to place a list/accordion above a button in Semantic UI?

Check out this rough code sandbox here There seems to be an issue with the accordion overflowing behind the button on the left side. I attempted to add style={{position: 'absolute', bottom:'2%', overflow: 'scroll'}} to the A ...

Issues with password confirmation function in Vuetify components

I am struggling to create a registration form where users must confirm their password by typing it in twice, but I can't seem to get Vuetify to validate that the two passwords match. Despite trying to set up rules for this validation, my code doesn&a ...

The gulp-stylus plugin fails to compile files due to an out-of-memory issue

Whenever I attempt to use the gulp-stylus plugin for compiling my stylus files, I encounter an issue. After running gulp stylus, gulp initiates the task "stylus," causing my CPU usage to spike up to 100%. Eventually, I receive this error message: FATAL ERR ...

What is the most effective approach to handling dependencies for an AngularJs 1.x web application?

Right now, I have a bunch of script elements pointing to cdn/local files, which isn't ideal. I'm considering declaring all necessary packages using npm/yarn and serving cdn files with self-hosted fallback. Is this a good idea? Would it be bette ...