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

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Obtain module-specific members through programmatic means

When working on a browser, the code may appear like this: //retrieve all enumerable properties of `this` function globalMems() { var g = this; var ret = {}; for (var prop in g) { ret[prop] = g[prop]; } return ret; } In Node.js, this does ...

JavaScript - Reveal a div when a grid item is clicked

I have created a grid with a 5x7 layout using divs. I am trying to achieve a feature similar to the Netflix interface where, upon clicking on a div, a larger div will appear beneath it. This larger div should expand to 100% width of the parent container, p ...

Navigating from a web address to making an asynchronous request using history.js

As I work on a small website that features multiple pages with similar layouts, I often find that only the content within a specific div varies. The rest of the elements such as navigation and header remain consistent throughout. To address this, I have s ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

Receiving an error message and identifying the specific line number within the catch

try{ cause error } catch(err){ console.log(err.lineNumber) //or console.log(err.line) } The error object has various properties like err.name, err.stack, and err.message, but I have been unable to find a way to log the line number of the error ...

Spinning a rectangular grid with JavaScript

I am currently developing my own version of Tetris. My main focus at the moment is creating a function that can rotate a 2D variable array by 90 degrees (or -90). For instance, if we have an array like: "-T-", "TTT" The expected outpu ...

Using a component in Vue 3 by importing it

Hello, I'm having an issue with importing a component in Vue 3. Here is the structure of my component : +src +App.vue +components +Navbar.vue In my App.vue file, I attempted to import the component using the following code : <scr ...

What are the best practices for presenting Motion JPEG binary data streams using Angular, Ionic, and JavaScript?

I am developing an application for a device that will receive a POST request and send back a binary data stream in the format of multipart/x-mixed-replace. My goal is to display this stream on a specific section of my app's homepage. After conducting ...

Gallery Pagination using JQuery is not working properly

I am experimenting with the jquery easy paginate plugin on a separate page of my Blogspot. The images are displaying properly, but the pagination and CSS are not showing up. I need to adjust my CSS to make this jQuery pagination work correctly. Can someone ...

"Adjusting the position of series data container in Highcharts JS to optimize

Currently, I am utilizing highcharts along with highcharts-ng. My goal is to adjust the position of the container for series Data (where the number 80 is displayed below) slightly higher as it is currently overlapping with the numbers 200 and -200 in the t ...

The log indicates that there are two distinct IP addresses associated with the user

I find that this question may be better suited for another Stack Exchange board, and I am open to migrating it there if needed. In the development of a web application, we record certain event information to assist in diagnosing any potential issues. One ...

`There is a lack of props validation in the react/prop-types``

As I set up my Next-React app on Netlify, I encountered an error in the deploy log: Netlify deploy log indicates: "Error: 'Component' is missing in props validation", "Error: 'pageProps' is missing in props validation" within my ./page ...

JavaScript encoding the text

Looking for a straightforward JavaScript function to encrypt text data from a textarea using a key (the key being the user's password stored as a hashed session variable, outputted by PHP into a field). The objective is to have the content of the tex ...

Using jQuery to append content with a variable as the source

Recently delving into jQuery and encountering an issue with getting my variable inside src when using append. Either it's not functional at all, or just displaying the variable name in string form in the console. Here is the code causing trouble: va ...

Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious. JS const gri ...

What is the best way to utilize RxJs for streaming HostListener events?

Although I've found plenty of resources on binding Angular HostListeners, I'm curious about using RxJs to stream it instead: @HostListener('document:click', ['$event']) handleClick(event: Event) { // etc } I want to cre ...

Updating data in Redux triggers a refresh of Material UI table data

Utilizing the material-ui data table component to showcase data, enabling users to update and save information via a form when clicking on a row. Implemented react-redux for state management and dispatching updated rows to the existing data. However, despi ...

What is the best way to retrieve the 'date,time' column from a MySQL database and use it as input for the google chart DateRangeFilter?

I am facing an issue with a column in my dataset that contains date-time values, such as '2017-2-2 10:30:20'. I need to use these rows as an input for a Date Range Filter in Google Chart. Can someone guide me on how to achieve this? I attempted ...