tha*_*ksd 3 javascript vue.js vuejs2
我有一个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;
},
}
Run Code Online (Sandbox Code Playgroud)
但是我希望已经可以引用该组件实例的属性。像这样:
export default {
data() {
return { globalVar: this.$store.state.var };
},
methods: {
foo() { console.log('foo') };
},
watch: {
globalVar() {
if (this.$isComponentActive) {
this.foo();
}
},
},
}
Run Code Online (Sandbox Code Playgroud)
在<keep-alive>标签的文档中找不到类似的内容。而且,查看Vue实例,它似乎没有它的属性。但是,有人知道我可以通过Vook实例自己获取“激活”状态而不必自己通过钩子维护它的方法吗?
也许您可以使用_inactive(基于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()
}
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)