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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM