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

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

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

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实例的"激活"状态,而不必自己通过钩子来维护它?

推荐答案

您可能可以使用_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>

Vue.js相关问答推荐

将事件监听器绑定到动态元素

Visual Studio代码中的VUE/VLAR扩展不断崩溃:JS/TS语言服务立即崩溃5次…

我可以将Created()中内置的内容传递给Provide属性吗?

用于循环数组的模板元素内的条件渲染

无法在cPanel/SSH上构建 | Laravel + Vue优化

为什么我在 Vue npm run serve 的 localhost 中得到无法获取

两个div元素之间的vue2过渡

Webpack 导入的模块不是函数

正确使用 Vue $refs

如何在Typescript语言Vuejs中使用watch功能?

可以同时使用 Tailwind css 和 Bootstrap 4 吗?

apache上的Vue-router,子目录下的SPA,只能通过重定向访问页面

包含 Vue.js v-if 和 v-for 指令的 HTML 标签在加载时flash

动态注册本地 Vue.js 组件

vue-cli-service build --target lib 导入为 lib 时丢失图像路径

构建 Vue.js 应用程序时 JavaScript 堆内存不足

如何在 Vue.js 插槽范围内传递方法

Vue 2 转换不起作用

VS Code - 在 .vue 文件中启用 autoClosingTags 选项

在 vue js 中的何处以及如何存储 API 端点?