How to destroy a VueJS component that is being cached by

前端 未结 4 1547
天涯浪人
天涯浪人 2021-01-13 17:16

I have a Vue component that\'s kept alive using Vue\'s element for caching purposes. However, the problem I am having right now is that once I sign out of one account and c

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 17:47

    I had the same problem and I solved it by using an array of cached components and bus event.

    Here is my HTML keep-alive App.vue:

    
      
    
    

    Here is what I'm doing in the created() life cycle:

       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)
            }
          })
        }
    

    And inside another component just trigger the event and send the component to remove in parameter.

    Another.vue

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

    If you don't know how to make a bus event there are lot of tutorials on the internet like this to do that. But bus event is my way to do that and you can use everything you want like a child emitter or Vuex. That I want to show is to use an array of components to manage your cache. All you have to do is to add or remove your components in the array.

提交回复
热议问题