0

I use v-for to generate task tabs.

Tasks can be created by users, and after users have created a new task I want the UI changing to the newly created tab automatically.

i.e. After a new tab has been added to the dom tree, itself click event will be triggered and the callback function activateTask will execute.

<template>
  <v-container>
    <v-btn @click="createNewTask"></v-btn>
    <v-tabs>
      <v-tab v-for="task in tasks" :key="task.uuid" @click="activateTask">
        {{ task.name }}
      </v-tab>
    </v-tabs>
  </v-container>
</template>

<script>
export default {
  data: {
    tasks: [],
  },
  method: {
    createNewTask() {
      this.tasks.push({
        uuid: util.generateUUID(),
        name: "name",
      });
    },
  },
};
</script>
yihsiu
  • 78
  • 5
  • I will put the name of the new task to a property `activeTabName` and make the tab container pre-select a tab based on this property. something like ` – lastr2d2 Dec 25 '20 at 07:08
  • Thank you. v-model may work! Trying it now. – yihsiu Dec 25 '20 at 07:32

2 Answers2

0

Figure out a way that using the update hook and a variable to check whether a new tab dom is created. If true select the last child node from dom tree and dispatch click event.

So ugly .

  updated() {
    this.$nextTick(() => {
      if (!this.newTaskCreated) {
        return
      }
      this.$el.querySelectorAll('.task-tab:last-child')[0].dispatchEvent(new Event('click'))
      this.newTaskCreated = false
    })
  }
yihsiu
  • 78
  • 5
0

You can bind v-tabs with v-model to control active-tab.

<template>
  <v-container>
    <v-btn @click="createNewTask"></v-btn>
    <v-tabs v-model="currentTab">
      <v-tab v-for="task in tasks" :key="task.uuid" @click="activateTask">
        {{ task.name }}
      </v-tab>
    </v-tabs>
  </v-container>
</template>

<script>
export default {
  data: {
    tasks: [],
    currentTab: null
  },
  method: {
    createNewTask() {
      this.tasks.push({
        uuid: util.generateUUID(),
        name: "name",
      });
      this.currentTab = this.tasks.length-1
    },
  },
};
</script>
Nilesh Patel
  • 3,193
  • 6
  • 12
  • It works! It will change to the new tab! But how to trigger click event. The click handler will trigger other events to update sibling components. – yihsiu Dec 25 '20 at 08:35
  • In my project I can just call activateTask in the end of createNewTask(). Thank you. – yihsiu Dec 25 '20 at 08:40