vue keep-alive 生命周期
父组件
<!-- --><template>
<div class="">
<keep-alive>
<testa v-if="test"></testa>
<testb v-else></testb>
</keep-alive>
<button @click="change">test change</button>
</div>
</template>
<script>
import testa from "./testA";
import testb from "./testB";
export default {
components: { testa,testb, },
data() {
return {
test:true
};
},
computed: {},
watch: {
name: {
handler(val, oldVal) {
/* ... */
},
deep: true,
immediate: true
}
},
methods: {
change(){
this.test = !this.test;
}
}
};
</script>
组件A:
<!-- --><template>
<div class="">
about-componnet
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
computed: {},
watch: {
name: {
handler(val, oldVal) {
/* ... */
},
deep: true,
immediate: true
}
},
methods: {},
beforeCreate() {
console.log("A--beforeCreate");
},
created() {
console.log("A--created");
},
beforeMount() {
console.log("A--beforeMount");
},
mounted() {
console.log("A--mounted");
},
beforeDestroy() {
console.log("A--beforeDestroy");
},
activated() {
console.log("A--activated");
},
deactivated() {
console.log("A--deactivated");
}
};
</script>
组件B:
<!-- --><template>
<div class="">
about-componnet
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
computed: {},
watch: {
name: {
handler(val, oldVal) {
/* ... */
},
deep: true,
immediate: true
}
},
methods: {},
beforeCreate() {
console.log("B--beforeCreate");
},
created() {
console.log("B--created");
},
beforeMount() {
console.log("B--beforeMount");
},
mounted() {
console.log("B--mounted");
},
beforeDestroy() {
console.log("B--beforeDestroy");
},
activated() {
console.log("B--activated");
},
deactivated() {
console.log("B--deactivated");
}
};
</script>
切换组件A和组件B,控制台打印:
// A组件首次激活A--beforeCreate
A--created
A--beforeMount
A--mounted
A--activated
// B组件首次激活,A组件失活
B--beforeCreate
B--created
B--beforeMount
A--deactivated
B--mounted
B--activated
// B组件失活,A组件激活
B--deactivated
A--activated
// A组件失活,B组件激活
A--deactivated
B--activated
结论:
- 首次激活时,activated都在mounted后。
- 再次激活时,本组件只走activated(另外一组件先失活deactivated)
- 组件失活时,均不走beforeDestroy和destroyed
以上是 vue keep-alive 生命周期 的全部内容, 来源链接: utcz.com/z/378669.html