2

I am using Vue 1.0.

  1. I have a UI with tabs.
  2. In each tab, there's a component that should load in its own data (via ajax).
  3. I don't want to load every tab's component's data at once.
  4. I only want to load the data once.

If I use v-if on the component and place the loading code in ready(), it loads every time the tab is selected. This is because v-if destroys and recreates the component. Is there a keep-alive equivalent for v-if?

If I use v-show, all tabs load at once. Is there a hook for when the component becomes visible?

Edit: because the comments keep mentioning dynamic components. I want to emphasise that I can't use dynamic components as the tabs require different properties.

10

1 Answer 1

2

You can use v-if together with v-show. When a tab is activated you set a property on it that is bound to the v-if. That makes the tab load. You do not unset that property.

A top-level property tracks which tab is currently displayed, and you use that in your v-show expression.

In the example below, each tab "loads" the current time at startup after a half-second delay. As you switch between tabs, you will see that each tab keeps its own time, it does not reload it each time it is displayed.

var baseComponent = Vue.extend({
  data: function() {
    return {
      ajax: null
    }
  },
  created() {
    setTimeout(() => this.ajax = Date.now(), 500);
  }
});

Vue.component("tab-one", baseComponent.extend({
  template: `<div>Template for tab 1 {{ajax}}</div>`
}));

Vue.component("tab-two", baseComponent.extend({
  template: `<div>Template for tab 2 {{ajax}}</div>`
}));

Vue.component("tab-three", baseComponent.extend({
  template: `<div>Template for tab 3 {{ajax}}</div>`
}));

new Vue({
  el: '#app',
  data: {
    tabs: [{
        label: 'Tab 1',
        component: 'tab-one',
        wasLoaded: false
      },
      {
        label: 'Tab 2',
        component: 'tab-two',
        wasLoaded: false
      },
      {
        label: 'Tab 3',
        component: 'tab-three',
        wasLoaded: false
      }
    ],
    activeTab: null
  },
  methods: {
    activate: function(tab) {
      tab.wasLoaded = true;
      this.activeTab = tab;
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.10/vue.min.js"></script>
<div id="app">
  <div>
    <div class="tabs">
      <button v-for="tab in tabs" @click="activate(tab)">
        {{ tab.label }}
      </button>
      <tab-one v-if="tabs[0].wasLoaded" v-show="activeTab === tabs[0]"></tab-one>
      <tab-two v-if="tabs[1].wasLoaded" v-show="activeTab === tabs[1]"></tab-two>
      <tab-three v-if="tabs[2].wasLoaded" v-show="activeTab === tabs[2]"></tab-three>
    </div>
  </div>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.