You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
<!DOCTYPE html>
|
|
|
|
<html lang="en">
|
|
|
|
<head>
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
<title>分析生命周期</title>
|
|
|
|
<script type="text/javascript" src="../vue.js"></script>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<div id="root" x="1">
|
|
|
|
<h2>当前的n值是:{{n}}</h2>
|
|
|
|
<button @click="add">n+1</button>
|
|
|
|
<button @click="bye">销毁vm</button>
|
|
|
|
</div>
|
|
|
|
<script type="text/javascript">
|
|
|
|
Vue.config.productionTip = false // 组织开发环境提示
|
|
|
|
|
|
|
|
// 创建Vue实例
|
|
|
|
const vm = new Vue({
|
|
|
|
el: '#root',
|
|
|
|
// template: `
|
|
|
|
// <div>
|
|
|
|
// <h2>当前的n值是:{{n}}</h2>
|
|
|
|
// <button @click="add">n+1</button>
|
|
|
|
// </div>
|
|
|
|
// `,
|
|
|
|
data: {
|
|
|
|
n: 1,
|
|
|
|
},
|
|
|
|
methods: {
|
|
|
|
add() {
|
|
|
|
console.log("add")
|
|
|
|
this.n++
|
|
|
|
},
|
|
|
|
bye() {
|
|
|
|
console.log("bye")
|
|
|
|
this.$destroy()
|
|
|
|
}
|
|
|
|
},
|
|
|
|
watch: {
|
|
|
|
n() {
|
|
|
|
console.log("n变了")
|
|
|
|
}
|
|
|
|
},
|
|
|
|
// 常用的生命周期包含 mounted和beforeDestroy
|
|
|
|
// mounted: 发送ajax请求、启动定时器、绑定自定义事件、订阅消息等(初始化操作)
|
|
|
|
// beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等(收尾工作)
|
|
|
|
// 初始化步骤1, 初始化了生命周期和事件,但是没有开始数据代理
|
|
|
|
beforeCreate(){
|
|
|
|
console.log("beforeCreate")
|
|
|
|
console.log(this)
|
|
|
|
// debugger
|
|
|
|
},
|
|
|
|
// 初始化步骤2,完成数据监测,数据代理
|
|
|
|
created() {
|
|
|
|
console.log("created")
|
|
|
|
console.log(this)
|
|
|
|
// debugger
|
|
|
|
},
|
|
|
|
// Vue开始解析模板,在内存中生成虚拟DOM,但未渲染页面,此时对DOM的操作都会在渲染真实DOM时失效
|
|
|
|
beforeMount() {
|
|
|
|
console.log("beforeMount")
|
|
|
|
console.log(this)
|
|
|
|
document.querySelector('h2').innerText = "Test"
|
|
|
|
// debugger
|
|
|
|
},
|
|
|
|
// 将虚拟DOM渲染成真实DOM, 完成渲染后所有DOM操作都会生效,此时完成初始化操作
|
|
|
|
mounted() {
|
|
|
|
console.log("mounted")
|
|
|
|
console.log(this)
|
|
|
|
// debugger
|
|
|
|
},
|
|
|
|
// 当数据更新后触发更新流程,此时data数据已更新,并步骤之后会生成新的虚拟DOM并与老的虚拟DOM做对比,执行updated来将差异重新渲染
|
|
|
|
beforeUpdate() {
|
|
|
|
console.log("beforeUpdate")
|
|
|
|
console.log(this.n)
|
|
|
|
console.log(this.$el)
|
|
|
|
// debugger
|
|
|
|
},
|
|
|
|
// 完成重新渲染
|
|
|
|
updated() {
|
|
|
|
console.log("updated")
|
|
|
|
console.log(this.n)
|
|
|
|
// debugger
|
|
|
|
},
|
|
|
|
// 完全销毁一个vm实例,清理它与实例的连接,解绑全部指令和自定义监听事件
|
|
|
|
beforeDestroy() {
|
|
|
|
console.log("beforeDestroy")
|
|
|
|
this.add()
|
|
|
|
debugger
|
|
|
|
},
|
|
|
|
// 完成销毁
|
|
|
|
destroyed() {
|
|
|
|
console.log("destroyed")
|
|
|
|
}
|
|
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
</body>
|
|
|
|
</html>
|