Exploring VueJS watchers: How to get started?

Struggling to grasp the concept of Watchers in VueJS, particularly when trying to implement them for tracking tab changes and resetting values. Even though I have set up a watch with parameters like `oldValue` and `newValue`, their usage remains unclear to me.

For reference, you can check out this CodePen.

Below is a complete example showcasing the scenario:

new Vue({
  el: "#app",
  data() {
    return {
      tabs: ["Tab1", "Tab2"],
      activeTab: 0,
      headers: [{
          text: "Dessert (100g serving)",
          align: "left",
          value: "name"
        },
        {
          text: "Calories",
          value: "calories"
        }
      ],
      items: [{
          name: "Ice cream sandwich",
          calories: 237
        },
        {
          name: "Frozen Yogurt",
          calories: 159
        }
      ],
      selected: []
    };
  },
  methods: {
    toggleAll() {
      if (this.selected.length) this.items = [];
      else this.selected = this.items.slice();
    }
  },
  watch: {
    activeTab: (oldValue, newValue) => {
      if (oldValue !== newValue) {
        this.selected = [];
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8aeadbdacb1bea198e9f6edf6e9ec">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3d5d6c6d7cac5dae3928d968d9297">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-tabs fixed-tabs v-model="activeTab">
      <v-tab v-for="tab in tabs" :key="tab">
        {{ tab }}
      </v-tab>
      <v-tab-item v-for="tab in tabs" :key="tab">
        <v-data-table v-model="selected" :headers="headers" :items="items" select-all item-key="name" class="elevation-1" hide-actions>
          <template v-slot:headers="props">
            <tr>
              <th>
                <v-checkbox :input-value="props.all" :indeterminate="props.indeterminate" primary hide-details @click.stop="toggleAll"></v-checkbox>
              </th>
              <th v-for="header in props.headers" :key="header.text">
                <v-icon small>arrow_upward</v-icon>
                {{ header.text }}
              </th>
            </tr>
          </template>
          <template v-slot:items="props">
            <tr :active="props.selected" @click="props.selected = !props.selected">
              <td>
                <v-checkbox :input-value="props.selected" primary hide-details></v-checkbox>
              </td>
              <td>{{ props.item.name }}</td>
              <td>{{ props.item.calories }}</td>
            </tr>
          </template>
        </v-data-table>
      </v-tab-item>
    </v-tabs>
  </v-app>
</div>

If anyone could provide insight on utilizing the watch feature effectively in this context, your assistance would be greatly appreciated. Thank you!

Answer №1

Your implementation of the activeTab function using a fat arrow is causing issues because it lacks a proper reference to this.

To resolve this, update your code to:

activeTab: function (oldValue, newValue) { // use function instead of =>
  if (oldValue !== newValue) {
    this.selected = [];
  }
}

Additionally, there seems to be an error in your code related to the check all box.

It is recommended to declare all top-level functions with function. Utilize => only within nested functions when access to this is needed.

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

An issue has arisen when trying to fetch and parse data using React and JavaScript

I am currently facing some challenges with fetching data from an API and displaying it using React. I have encountered errors and I am struggling with parsing the JSON response from the API. I believe that converting the response into an array may help res ...

Updating the content of a window without the need to refresh the page using JavaScript

Is there a way to navigate back to the previous window in chat_user without refreshing the entire page when the back button is clicked? Below is the code I have tried: <a href="" onclick="window.history.go(-1); return false;">back</a> ...

The options object provided for Ignore Plugin initialization in Webpack 5.21.2 does not conform to the API schema, resulting in an error

Here is the setup of my webpack.config.js on a backend server running webpack version 5.21.1: /* eslint-disable */ const path = require('path'); const webpack = require('webpack'); module.exports = { target: 'node', modul ...

Combining Multiple Values from Various Form Elements using Jquery's .sum() Method

Below is the form provided for calculation purposes... <form> <label>First:</label> <select class="first"> <option value="0">Earth</option> <option value="1">Mars</option> <option value="2 ...

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...

Sending values to URL using the <a> tag in HTML

I currently have the selected language stored in a variable (var lan= urlParam('language')). I am trying to pass this language as a parameter (without PHP) in a URL within an "a" tag, like so: <a href="http://hotelscombined.sitewish.gr/HotelN ...

Utilizing Node.js and Node-Postgres: Organizing Database Queries in Models

In order to enhance the efficiency of my code, I am looking to modularize my queries by organizing them into functions with appropriate names for their tasks. Instead of cluttering up the req, res functions (controllers), I aim to encapsulate them in a se ...

Guide on using axios in vue.js to interact with the API

I need help with a functionality on my website where users can select a car brand from a list of radio buttons. After selecting a brand, I want to retrieve an array of models from the server and display them on a new page. Can someone guide me on what spec ...

Vue's smooth scrolling in Nuxt.js was not defined due to an error with the Window

There seems to be an issue with adding vue smooth scroll to my nuxt.js project as I'm encountering the "window is not defined error". The steps I followed were: yarn add vue2-smooth-scroll Within the vue file, I included: import Vue from 'vue ...

Communicating between PHP chat client and server

Currently, I am developing a basic PHP web chat application that interacts with a MySQL database. The communication is facilitated through AJAX requests - when a user posts a message, it gets saved in the database. function sendData(){ var textData = $(& ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...

Accessing variables from an external script in jsdom

Here is a simple example of jsdom code using the script parameter. Despite my best efforts to reference external JS files, I keep running into this issue: ReferenceError: exVar is not defined Does anyone know what might be causing this problem and how ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

Tips for creating a highly adaptable code base- Utilize variables

Can anyone help me optimize this lengthy and cumbersome code in HTML and JS? I want to make it more efficient by using variables instead of repeating the same code over and over. In the HTML, I've used href links to switch between different months, w ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Error message "invalid function call this.job.execute" when using Node.js node-schedule npm package

Having just started with nodejs, I created a nodejs program and set it to run every minute using the node-schedule library. However, after running for some time and producing several logs in the console, I encountered an error stating that this.job.execute ...

Is there a way to set it up so that my section remains hidden until the submit button is pressed, rather than disappearing every time I input a single character?

How can I modify the behavior in vue.js so that a certain section is hidden only after the user clicks on the submit button? Currently, the section disappears every time a single letter is entered. I want the visibility toggling with V-if and V-else to o ...

Tips on retrieving the image URL from Aws s3 and saving it in mongodb

Can anyone help me with retrieving the URL location of an image from AWS s3 and storing it in MongoDB using mongoose? Currently, when I try to console log the req.file.location value, it shows up as undefined. I have also attempted to console log uploadFil ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...