vue结合keep-alive和vuex给页面做动态缓存
[ 2019/10/31, Vue , 1512阅, 0评 ]

项目中有类似需求:列表进详情,详情再返回列表,列表保持之前的状态,而其他页面进列表则重新渲染。

结合项目实际情况,最终实现方法:结合beforeRouteEnter和beforeRouteLeave钩子然后用keep-alive做缓存。

有关keep-alive的作用及使用方法本文将不再赘述(详见官方文档

栗子如下,父组件:

  1. <template>
  2. <div id="app">
  3. <keep-alive :include="cachedPages">
  4. <router-view />
  5. </keep-alive>
  6. </div>
  7. </template>
  8. <script>
  9. import { mapState } from 'vuex'
  10. export default {
  11. computed: {
  12. ...mapState({
  13. cachedPages: state => state.cachedPages
  14. })
  15. }
  16. }
  17. </script>

列表组件:

  1. export default {
  2. name: 'listComponentName',
  3. beforeRouteEnter(to, from, next) {
  4. next(vm => {
  5. vm.$store.commit('ADD_CACHED_PAGE', 'listComponentName')
  6. })
  7. },
  8. beforeRouteLeave(to, from, next) {
  9. // 详情组件路由假如是 /list/detail/123
  10. if (!to.path.includes('/list/detail/')) {
  11. this.$store.commit('REMOVE_CACHED_PAGE', 'listComponentName')
  12. }
  13. next()
  14. }
  15. }

vuex:

  1. export default new Vuex.Store({
  2. state: {
  3. cachedPages: []
  4. },
  5. mutations: {
  6. ADD_CACHED_PAGE(state, payload) {
  7. !state.cachedPages.includes(payload) && state.cachedPages.push(payload)
  8. },
  9. REMOVE_CACHED_PAGE(state, payload) {
  10. state.cachedPages = state.cachedPages.filter(item => item !== payload)
  11. }
  12. }
  13. })

相关资料

有朋自远方来...评论一下呗O(∩_∩)O