前端必知必会-Vue “activated”和“deactivated”生命周期钩子


Vue “activated”和“deactivated”生命周期钩子

正如我们在此页面上看到的,我们有已安装和未安装的生命周期钩子,用于在组件被移除或添加到 DOM 时使用。

已激活和已停用生命周期钩子用于在添加或移除缓存的动态组件(但不从 DOM 中删除)时使用。以下示例中使用 <KeepAlive> 标记来缓存动态组件。

示例
CompOne.vue:

<template>
<h2>组件</h2>
<p>以下是每次运行“已安装”或“已激活”钩子的日志。</p>
<ol ref="olEl"></ol>
<p>您还可以在控制台中查看这些钩子的运行时间。</p>
</template>

<script>
export default {
      
      
mounted() {
      
      
console.log("mounted");
const liEl = document.createElement("li");
liEl.innerHTML = "已安装";
this.$refs.olEl.appendChild(liEl);
},
activated() {
      
      
console.log("已激活");
const liEl = document.createElement("li");
liEl.innerHTML = "已激活";
this.$refs.olEl.appendChild(liEl);
}
}
</script>

<style>
li {
      
      
background-color: lightcoral;
width: 5em;
}
</style>

App.vue:

<template>
<h1>“activated”生命周期钩子</h1>
<p>在此“activated”钩子示例中,我们检查组件是否已使用 <KeepAlive> 正确缓存。</p>
<p>如果组件已使用 <KeepAlive> 正确缓存,我们期望“mounted”钩子在第一次包含组件时运行一次(必须在第一次添加到 DOM 中),并且我们期望“activated”钩子在每次包含组件时运行(也是第一次)。</p>
<button @click="this.activeComp = !this.activeComp">包含组件</button>
<div>
<KeepAlive>
<comp-one v-if="activeComp"></comp-one>
</KeepAlive>
</div>
</template>

<script>
export default {
      
      
data() {
      
      
return {
      
      
activeComp: false
}
}
}
</script>

<style scoped>
div {
      
      
border: dashed black 1px;
border-radius: 10px;
padding: 20px;
margin-top: 10px;
background-color: lightgreen;
}
</style>

让我们扩展上面的示例,看看 activated 和 deactivated 钩子是如何工作的。我们还可以使用 mounted 和 unmounted 钩子,这样我们就可以看到 mounted 钩子在第一次添加缓存组件时运行一次,而 unmounted 钩子永远不会为缓存组件运行。

示例
CompOne.vue:

<template>
<h2>组件</h2>
<p>下面是每次运行“activated”、“deactivated”、“mounted”或“unmounted”钩子时的日志。</p>
<ol ref="olEl"></ol>
<p>您还可以在控制台中查看这些钩子何时运行。</p>
</template>

<script>
export default {
      
      
mounted() {
      
      
this.logHook("mounted");
},
unmounted() {
      
      
this.logHook("unmounted");
},
activated() {
      
      
this.logHook("activated");
},
deactivated() {
      
      
this.logHook("deactivated");
},
methods: {
      
      
logHook(hookName) {
      
      
console.log(hookName);
const liEl = document.createElement("li");
liEl.innerHTML = hookName;
this.$refs.olEl.appendChild(liEl);
}
}
}
</script>

<style>
li {
      
      
background-color: lightcoral;
width: 5em;
}
</style>

App.vue:

<template>
<h1>“activated”和“deactivated”生命周期钩子</h1>
<p>在此“activated”和“deactivated”钩子示例中,我们还可以看到“mounted”和“unmounted”钩子何时以及是否运行。</p>
<button @click="this.activeComp = !this.activeComp">包含组件</button>
<div>
<KeepAlive>
<comp-one v-if="activeComp"></comp-one>
</KeepAlive>
</div>
</template>

<script>
export default {
      
      
data() {
      
      
return {
      
      
activeComp: false
}
}
}
</script>

<style scoped>
div {
      
      
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin-top: 10px;
    background-color: lightgreen;
}
</style>

总结

本文介绍了Vue “activated”和“deactivated”生命周期钩子的使用,如有问题欢迎私信和评论