我正在使用Vue 1.0。
如果我在组件上使用v-if并将加载代码放在ready()中,则每次选择选项卡时都会加载它。这是因为v-if会破坏并重新创建组件。是否存在v-if的保持等效值?
如果我使用v-show,则会立即加载所有标签页。当组件变得可见时是否有钩子?
编辑:因为评论不断提及动态组件。我想强调我不能使用动态组件,因为标签需要不同的属性。
答案 0 :(得分:2)
您可以将v-if
与v-show
一起使用。激活选项卡后,在其上设置绑定到v-if
的属性。这使标签加载。你没有取消该财产。
顶级属性会跟踪当前显示的标签,并在v-show
表达式中使用该标签。
在下面的示例中,每个标签"加载"延迟半秒后启动时的当前时间。当您在标签之间切换时,您会看到每个标签都保留了自己的时间,每次显示时都不会重新加载。
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;
}
}
});
&#13;
<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>
&#13;