有的時候,在不同組件之間進行動態切換是非常有用的,比如在一個多標籤的界面裡
可以通過 Vue 的 <component>
元素加一個特殊的 is
特性來實現:
<div id="app">
<div class="box">
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="#"
:class="{'active': currentView == 'component-one'}"
@click.prevent="currentView = 'component-one'">分頁一
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"
:class="{'active': currentView == 'component-two'}"
@click.prevent="currentView = 'component-two'">分頁二
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"
:class="{'active': currentView == 'component-three'}"
@click.prevent="currentView = 'component-three'">分頁三
</a>
</li>
</ul>
<div :is="currentView"></div>
</div>
</div>
Vue.component('component-one', {
template: '<p>這裡是分頁一的內容.<p>',
});
Vue.component('component-two', {
template: '<p>這裡是分頁二的內容<p>',
});
Vue.component('component-three', {
template: '<p>這裡是分頁三的內容<p>',
});
new Vue({
el: '#app',
data :{
currentView : 'component-one'
}
})
在動態切換的時候,如果要保存資料的狀態,就可以使用<keep-alive>
,
這樣就可以避免切換的時候重新載入元件而導致資料的流失。
沒加<keep-alive>
有加<keep-alive>
<div id="app">
<div class="box">
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="#"
:class="{'active': currentView == 'component-one'}"
@click.prevent="currentView = 'component-one'">分頁一</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"
:class="{'active': currentView == 'component-two'}"
@click.prevent="currentView = 'component-two'">分頁二</a>
</li>
</ul>
<keep-alive>
<div :is="currentView"></div>
</keep-alive>
</div>
</div>
Vue.component('component-one', {
template: '<div><p>這裡是分頁一的內容<p><input type="text" placeholder="填寫內容"></input></div>',
});
Vue.component('component-two', {
template: '<p>這裡是分頁二的內容<p>',
});
new Vue({
el: '#app',
data :{
currentView : 'component-one'
}
})