生命周期
- vue的生命周期有11个状态。分别是
beforeCreate
、created
、beforeMount
、mounted
、brforeUpdate
、updated
、activated
、deactivated
、beforeDestroy
、destroyed
、errorCaptured
。 - 关于
activated
、deactivated
的使用,参考一下大佬们的文章的解释,例子 errorCaptured
,用来捕获来自组件的错误。此钩子会收到三个参数:错误对象、发生错误的组件实例以及一个包含错误来源信息的字符串。此钩子可以返回 false 以阻止该错误继续向上传播。- 案例
<div id="app">{{msg}}</div>
Vue.component("ComponentA", {
methods: {
handleClick() {
this.count++;
},
},
data() {
return {
count: 0,
};
},
beforeCreate() {
console.log("子组件创建之前-bc");
},
created() {
console.log("子组件创建之后-c");
},
beforeMount() {
console.log("子组件挂载之前-bm");
},
mounted() {
console.log("子组件挂载之后-m");
},
brforeUpdate() {
console.log("子组件更新之前-bu");
},
updated() {
console.log("子组件更新之后-u");
},
beforeDestroy() {
console.log("子组件销毁之前-bdd");
},
destroyed() {
console.log("子组件销毁之后-d");
},
template: `<div>ComponentA
{{count}}
<button @click="handleClick">click</button>
</div>`,
});
app = new Vue({
el: `#app`,
template: `
<div>{{msg}}
<ComponentA></ComponentA>
</div>`,
data: {
msg: "hello world",
},
beforeCreate() {
console.log("父组件创建之前-bc");
},
created() {
console.log("父组件创建之后-c");
},
beforeMount() {
console.log("父组件挂载之前bm");
},
mounted() {
console.log("父组件挂载之后m");
},
brforeUpdate() {
console.log("父组件更新之前bu");
},
updated() {
console.log("父组件更新之后u");
},
beforeDestroy() {
console.log("父组件销毁之前bd");
},
destroyed() {
console.log("父组件销毁之后d");
},
});
- 结果如下
![生命周期](https://i-blog.csdnimg.cn/blog_migrate/8aef50824ffd749055a272e5a92fc0f7.png)
观察总结:
- create两个钩子是元素创建被调用的,
beforeCreate
元素创建之前被调用,created
元素创建之后被调用,在这个钩子里可以进行后端接口对接。在上边的例子中create钩子元素创建前后被调用。 - mount两个钩子是元素挂载(即渲染视图)被调用的,
beforeMount
元素被挂载之前被调用,mounted
元素被挂载之后被调用,在这个钩子里也可以进行后端接口对接。在上边的例子中mount钩子元素挂载前后被调用 - update两个钩子是元素更新被调用,
brforeUpdate
元素更新之前被调用,updated
元素更新之后被调用,在上边的例子中,当点击click按钮后,才会触发updated
钩子。 - destroy两个钩子时关闭页面被调用,一般很少用到。
重点:面试题!!!
- 在上边的例子中,父子组件生命周期钩子是这样的:父组件创建完成,接着创建子组件,等子组件创建、挂载完成最后,父组件再挂载。
点个赞再走呗