Skip to content
Advertisement

How to tell if a Vue component is active or not

I have a Vue component that is wrapped in a <keep-alive> tag to prevent re-rendering.

Within the component, I want to react to some change in global data by firing a method. But, I only want to fire the method if the component is currently active.

Right now, I’m doing something like this:

export default {
  data() {
    return { 
      globalVar: this.$store.state.var,
      isComponentActive: false,
    };
  },
  methods: {
    foo() { console.log('foo') };
  },
  watch: {
    globalVar() {
      if (this.isComponentActive) {
        this.foo();
      }
    },
  },
  activated() {
    this.isComponentActive = true;
  },
  deactivated() {
    this.isComponentActive = false;
  },
}
  

But I was hoping there was already a property of the component’s instance that I could reference. Something like this:

export default {
  data() {
    return { globalVar: this.$store.state.var };
  },
  methods: {
    foo() { console.log('foo') };
  },
  watch: {
    globalVar() {
      if (this.$isComponentActive) {
        this.foo();
      }
    },
  },
}

I can’t find anything like that in the documentation for the <keep-alive> tag. And, looking at the Vue instance, it doesn’t appear to have a property for it. But, does anyone know of a way I could get the “activated” state of the Vue instance without having to maintain it myself through the hooks?

Advertisement

Answer

Probably you can use _inactive (based on the source code at vue/src/core/instance/lifecycle.js ) to check whether the component is activated or not.

Vue.config.productionTip = false
Vue.component('child', {
  template: '<div>{{item}}</div>',
  props: ['item'],
  activated: function(){
    console.log('activated', this._inactive, this.item)
  },
  deactivated: function(){
    console.log('deactivated', this._inactive, this.item)
  },
  mounted: function(){
    console.log('mounted', this._inactive, this.item)
  },
  destroyed: function () {
    console.log('destroyed', this._inactive, this.item)
  }
})

new Vue({
  el: '#app',
  data() {
    return {
      testArray: ['a', 'b', 'c']
    }
  },
  methods:{
    pushItem: function() {
      this.testArray.push('z')
    },
    popItem: function() {
      this.testArray.pop()
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <button v-on:click="pushItem()">Push Item</button>
  <button v-on:click="popItem()">Pop Item</button>
  <div v-for="(item, key) in testArray">
    <keep-alive>
      <child :key="key" :item="item"></child>
    </keep-alive>
  </div>
</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement