如何销毁 <keep-alive> 缓存的 VueJS 组件

新手上路,请多包涵

我有一个 Vue 组件,它使用 Vue 的元素保持活动状态以进行缓存。但是,我现在遇到的问题是,一旦我注销一个帐户并在我的 Vue 应用程序上创建一个新帐户,我“保持活力”的组件就会反映给新用户(这显然不是与新用户相关)。

因此,我想在用户注销后销毁该组件。最好的方法是什么?

原文由 p4t 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 513
2 个回答

我设法通过以下方式解决了我的问题。本质上,如果用户已登录,则让仪表板保持活动状态。否则,不要让仪表板保持活动状态。每次路线更改时,我都会通过“观察”路线来检查用户是否登录或注销(见下文)。如果您正在阅读这篇文章并且有更优雅的解决方案 - 我很乐意听到它。

以下是我的根组件的代码

<template>
    <div id="app">
        <!-- if user is logged in, keep dashboard alive -->
        <keep-alive
            v-bind:include="[ 'dashboard' ]"
            v-if="isLoggedIn">
            <router-view></router-view>
        </keep-alive>
        <!-- otherwise don't keep anything alive -->
        <router-view v-else></router-view>
    </div>
</template>

<script>
    import firebase from "firebase";

    export default {
        name: 'app',
        data() {
            return {
                isLoggedIn: false // determines if dashboard is kept alive or not
            }
        },
        watch: {
            $route (to, from){ // if the route changes...
                if (firebase.auth().currentUser) { // firebase returns null if user logged out
                    this.isLoggedIn = true;
                } else {
                    this.isLoggedIn = false;
                }
            }
        }
    }
</script>

原文由 p4t 发布,翻译遵循 CC BY-SA 3.0 许可协议

我遇到了同样的问题,我通过使用一组缓存组件和总线事件解决了这个问题。

这是我的 HTML keep-alive App.vue:

 <keep-alive :include="cachedComponents">
  <router-view></router-view>
</keep-alive>

这是我在 created() 生命周期中所做的事情:

    created() {
      // Push Home component in cached component array if it doesn't exist in the array
      if (!this.cachedComponents.includes('Home')) {
        this.cachedComponents.push('Home')
      }

      // Event to remove the components from the cache
      bus.$on('clearCachedComponents', (data) => {
        // If the received component exist
        if (this.cachedComponents.includes(data)) {
          // Get the index of the component in the array
          const index = this.cachedComponents.indexOf(data)
          // Remove it from the array
          this.cachedComponents.splice(index, 1)
        }
      })
    }

在另一个组件内部,只需触发事件并发送组件以在参数中删除。

另一个.vue

 bus.$emit('clearCachedComponents', 'Home')

如果您不知道如何制作公交车活动,互联网上有很多 这样 的教程可以做到这一点。但总线事件是我这样做的方式,你可以使用任何你想要的东西,比如子发射器或 Vuex。我想展示的是使用一组组件来管理您的缓存。您所要做的就是在数组中添加或删除组件。

原文由 John 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题