vuejs切换视图同时保持状态

vuejs切换视图同时保持状态

http://cn.vuejs.org/guide/components.html#动态组件

动态组件

多个组件可以使用同一个挂载点,然后动态地在它们之间切换。使用保留的 元素,动态地绑定到它的 is 特性:

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。

posted @ 2016-06-28 21:03  CooMark  阅读(4889)  评论(0编辑  收藏  举报