vuejs切換視圖同時保持狀態
http://cn.vuejs.org/guide/components.html#動態組件
動態組件
多個組件可以使用同一個掛載點,然后動態地在它們之間切換。使用保留的
new Vue({
el: 'body',
data: {
currentView: 'home'
},
components: {
home: { /* ... */ },
posts: { /* ... */ },
archive: { /* ... */ }
}
})
<component :is="currentView">
<!-- 組件在 vm.currentview 變化時改變 -->
</component>
keep-alive
如果把切換出去的組件保留在內存中,可以保留它的狀態或避免重新渲染。為此可以添加一個 keep-alive 指令參數:
<component :is="currentView" keep-alive>
<!-- 非活動組件將被緩存 -->
</component>
路由
對於單頁應用,推薦使用官方庫 vue-router。詳細請查看它的文檔。
如果你只需要非常簡單的路由邏輯,可以這么做,監聽 hashchange 事件並使用動態組件:
示例:
<div id="app">
<component :is="currentView"></component>
</div>
Vue.component('home', { /* ... */ })
Vue.component('page1', { /* ... */ })
var app = new Vue({
el: '#app',
data: {
currentView: 'home'
}
})
// 在路由處理器中切換頁面
app.currentView = 'page1'
利用這種機制也可以非常容易地配合其它路由庫,如 Page.js 或 Director。