生命周期
生命周期函数:在一个组件的生命周期范围内某一阶段自动执行的函数
vue 官方生命周期图示
初始化
1、beforeCreate ()在实例生成之前自动执行 2、created()在实例生成之前自动执行 3、beforeMount () 在组件内容被渲染到页面之前调用 4、mounted()在组件内容被渲染到页面之后调用
const app = Vue.createApp({
data() {
return {
msg: "hello",
};
},
beforeCreate () {
console.log('beforeCreate');
},
created () {
console.log('created');
},
beforeMount () {
console.log(document.getElementById('app').innerHTML)
console.log('beforeMount');
},
template:`<h1>{{msg}}</h1>`,
mounted () {
console.log(111,document.getElementById('app').innerHTML)
},
更新状态
5、beforeUpdate()当数据发生变化调用,页面还没更新 6、updated ()数据发生变化,页面也更新完时 示例,将数据进行改变,可以查看到页面内容改变对应的钩子函数,大多数情况下使用beforeUpdate()
beforeUpdate () {
console.log(222,document.getElementById('app').innerHTML)
console.log('beforeUpdate');
},
updated () {
console.log(333,document.getElementById('app').innerHTML)
console.log('updated');
},
销毁vue实例
7、beforeUnmount() 当vue实例失效时,自动执行函数 8、unmounted() 当vue实例失效,dom完全销毁,自动执行函数
beforeUnmount() {
console.log(444, document.getElementById("app").innerHTML);
console.log("beforeUnmount");
},
unmounted() {
console.log(555, document.getElementById("app").innerHTML);
console.log("unMounted");
},
template: `<h1>{{msg}}</h1>`,
});
app.mount("#app");
setTimeout(() => {
app.unmount("#app");
}, 3000);
常用beforeUpdate();created();mounted()
捕获错误时调用
9、errorCaptured(err, instance, info) 全局的错误捕获
errorCaptured(err, instance, info) {
console.log(err, instance, info);
return false;
},
其他生命周期函数参考官方文档
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"></div>
<script>
const app = Vue.createApp({
data() {
return {
msg: "hello",
};
},
beforeCreate() {
console.log("beforeCreate");
},
created() {
console.log("created");
},
beforeMount() {
console.log("beforeMount");
},
mounted() {
console.log("mounted");
},
beforeUpdate() {
console.log(222, document.getElementById("app").innerHTML);
console.log("beforeUpdate");
},
updated() {
console.log(333, document.getElementById("app").innerHTML);
console.log("updated");
},
beforeUnmount() {
console.log(444, document.getElementById("app").innerHTML);
console.log("beforeUnmount");
},
unmounted() {
console.log(555, document.getElementById("app").innerHTML);
console.log("unMounted");
},
errorCaptured(err, instance, info) {
console.log(err, instance, info);
return false;
},
template: `<h1>{{msg}}</h1>`,
});
app.mount("#app");
setTimeout(() => {
app.unmount("#app");
}, 3000);
</script>
</body>
</html>
|