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>
is
directive. There is a point wherekeep-alive
is introduced and used in this jsfiddle jsfiddle.net/coligo/43kxkm3d/…