Reputation:
I am trying to use Watchers in VueJS but having bit of a hard time wrapping my head around them. For example in this case i have set up a watch
which checks for the tab i am on and if the tab changes it should reset the selected
value back to an empty array. Now i have set the parameters as oldValue
and newValue
but i am not quite sure how will i use those.
Check this codepen.
Here is the Complete example:-
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/[email protected]/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/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>
I am not quite sure how i will use that watch so if someone can help me with that, i sure would appreciate it. Thank you.
Upvotes: 0
Views: 594
Reputation: 12639
You're using a fat arrow function for activeTab
, it needs to be a normal function or it doesn't have a proper reference to this
Change to this:
activeTab: function (oldValue, newValue) { // function instead of =>
if (oldValue !== newValue) {
this.selected = [];
}
}
Also, there's an issue with your code when you use the check all box.
As a good rule of thumb, all top level functions should be declared using function
. Only use =>
within the functions themselves when a nested function needs access to this
Upvotes: 1