在VueJS中使用观察者吗?

问题描述 投票:0回答:1

我正在尝试在VueJS中使用Watchers,但是很难将它们包裹住。例如,在这种情况下,我已经设置了watch来检查我所在的标签页,如果标签页发生更改,则应将selected值重新设置为空数组。现在,我将参数设置为oldValuenewValue,但我不太确定如何使用这些参数。

检查此codepen

这里是完整的示例:-

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>

我不太确定我将如何使用那只手表,因此,如果有人可以帮助我,我当然会很感激。谢谢。

javascript vue.js vuetify.js watch
1个回答
0
投票

[您正在为activeTab使用粗箭头功能,它必须是普通功能,或者没有正确引用this

更改为此:

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

而且,使用全选框时,您的代码也有问题。

作为良好的经验法则,应使用function声明所有顶级函数。仅当嵌套函数需要访问=>

时,才在函数本身内使用this
© www.soinside.com 2019 - 2024. All rights reserved.