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!