每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。从开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、卸载等一系列过程,参考官网图片
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Vue</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<span v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">{{foo}}</span>
</div>
<script>
var obj = {
activeColor:'red',
fontSize:'12',
foo: '<font color="red">Hello Html Fragment</font>'
}
var vm = new Vue({
el: '#app',
data: obj,
beforeCreate:function()
{
console.log('beforeCreate...');
},
created:function()
{
console.log('create...');
},
beforeMount:function()
{
console.log('beforeMount...');
},
mounted:function()
{
console.log('mounted...');
},
beforeUpdate:function()
{
console.log('beforeUpdate...');
},
updated:function()
{
console.log('updated...');
},
beforeDestroy:function()
{
console.log('beforeDestroy...');
},
destroyed:function()
{
console.log('destroyed...');
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Vue</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<span v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">{{foo}}</span>
</div>
<script>
var obj = {
activeColor:'red',
fontSize:'12',
foo: '<font color="red">Hello Html Fragment</font>'
}
var vm = new Vue({
el: '#app',
data: obj,
beforeCreate:function()
{
console.log('beforeCreate...');
},
created:function()
{
console.log('create...');
//1秒后更新数据
setTimeout(()=>this.foo='Sun',1000);
},
beforeMount:function()
{
console.log('beforeMount...');
},
mounted:function()
{
console.log('mounted...');
},
beforeUpdate:function()
{
console.log('beforeUpdate...');
},
updated:function()
{
console.log('updated...');
},
beforeDestroy:function()
{
console.log('beforeDestroy...');
},
destroyed:function()
{
console.log('destroyed...');
}
})
</script>
</body>
</html>