【问题标题】:How to tell if a Vue component is active or not如何判断 Vue 组件是否处于活动状态
【发布时间】:2018-05-11 15:53:06
【问题描述】:

我有一个 Vue 组件,它被包裹在 <keep-alive> 标记中以防止重新渲染。

在组件中,我想通过触发一个方法来对全局数据的一些变化做出反应。但是,我只想在组件当前处于活动状态时触发该方法。

现在,我正在做这样的事情:

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;
  },
}

但我希望已经有一个可以引用的组件实例的属性。像这样的:

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

我在the documentation for the <keep-alive> tag 中找不到类似的内容。而且,查看 Vue 实例,它似乎没有属性。但是,有没有人知道一种方法可以让我获得 Vue 实例的“激活”状态,而无需自己通过钩子来维护它?

【问题讨论】:

  • 可能使用the directive=ref 是一种解决方案。使用<keep-alive> 为您的组件添加ref="test",然后通过this.$refs.test ? true : false 检查活动状态。
  • 那不行,即使组件被停用,组件的$refs 数组也会保留。除非您的意思是来自父范围,否则这对我没有帮助,因为我需要防止触发的方法在停用的组件中,而不是在父范围内。

标签: javascript vue.js vuejs2


【解决方案1】:

大概你可以使用_inactive(基于the source code at vue/src/core/instance/lifecycle.js )来检查组件是否被激活。

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>

【讨论】:

  • 是的,完美一定错过了。谢谢!
  • 你没有错过,它不是公共 api,可以随时更改。我想在实例上拥有这样的属性而不手动创建它...
【解决方案2】:

查看source code 看起来组件实例中的任何状态都没有改变。相反,该元素只是从缓存中添加或删除。所以不,我认为除了生命周期钩子之外别无选择。

【讨论】:

    【解决方案3】:

    使用 Vue 3 组合 API,您可以使用 onDeactivated 在组件中设置 inactive 标志属性

    https://v3.vuejs.org/api/options-lifecycle-hooks.html#deactivated

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      相关资源
      最近更新 更多