vue的生命周期分为:创建前/后,加载前/后,更新前/后,销毁前/后。
个人目前常用的是: 创建后,加载后。也就是created和mounted
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
{{mes}}
</div>
</body>
</html>
<script lang="js">
new Vue({
el:'#app',
data:{
mes:'mes'
},
// 创建前, 实例创建前,还没有data和methods属性
beforeCreate(){
console.log('beforeCreated');
},
// 创建后, 实例创建后, data和methods初始化,还没有开始编译模板。
created(){
console.log('created');
},
// 载入前, 已经编译好模板,但是还没有挂载到页面上。
beforeMount(){
console.log('beforeMounted');
},
// 载入后, 将已经编译好的模板挂到页面上。
mounted(){
console.log('mounted');
},
// 更新前, 数据更新之前执行函数,此时data的状态是最新的,但是页面上的数据是旧的。
beforeUpdate(){
console.log('beforeUpdate');
},
// 更新后, 页面上的数据重新渲染。
updated(){
console.log('updated');
},
// 销毁前, 实例准备销毁,但还没开始。
beforeDestory(){
alert('sss');
console.log('beforeDestory');
},
// 销毁后,实例已经销毁,所有的data和methods等都没有了。
destoryed(){
console.log('destoryed');
},
});
</script>
可以根据上面的实例代码进行调试观察,如果不会使用浏览器进行调试的请看下方的说明。
按F12打开调试界面,选择sources打开当前页面即可。