生命周期更新流程
当数据改变的时候,调用生命周期函数beforeupdate。此阶段页面和数据尚未保持同步。 通过下列代码观察网页中发现页面和数据确实未同步,点击页面中的自加按钮时,页面中两个地方,一个是1一个是2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>分析生命周期</title>
<script type="text/javascript" src="../vue.js">
Vue.config.productionTip = false
</script>
</head>
<body>
<div id="root">
<h1> 当前的n值是:{{ n }}</h1>
<button @click="add"> 点我n + 1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
const vm = new Vue({
el: '#root',
data() {
return {
n: 1
}
},
methods: {
add() {
this.n++
}
},
beforeCreate() {
console.log('beforeCrate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
},
beforeUpdate() {
console.log('beforeupdated');
console.log(this.n);
debugger
},
})
</script>
</body>
</html>
继续到updated生命周期函数,被调用后,我们发现页面中的数据统一了,点击自加按钮后都是2。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>分析生命周期</title>
<script type="text/javascript" src="../vue.js">
Vue.config.productionTip = false
</script>
</head>
<body>
<div id="root">
<h1> 当前的n值是:{{ n }}</h1>
<button @click="add"> 点我n + 1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
const vm = new Vue({
el: '#root',
data() {
return {
n: 1
}
},
methods: {
add() {
this.n++
}
},
beforeCreate() {
console.log('beforeCrate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
},
beforeUpdate() {
console.log('beforeupdated');
},
updated() {
console.log('updated');
console.log(this.n);
},
})
</script>
</body>
</html>
|