<body>
<div id="root">
<h2>让n加一:{{n}}</h2>
<button @click="add">加一</button>
<button @click="goodbye">销毁vm</button>
</div>
<script>
new Vue({
el: '#root',
data: {
n:1
},
methods: {
add() {
this.n++
},
goodbye() {
console.log('goodbye');
this.$destroy()
}
},
beforeCreate() {
console.log('beforecreate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
},
beforeUpdate() {
console.log('beforeUpdate')
console.log(this.n)
},
updated() {
console.log('updated');
},
beforeDestroy() {
console.log('beforeDestroy');
},
destroyed() {
console.log('destroyed');
}
})
</script>
</body>
- this:都指向vm或组件对象;
- beforeCreate:初始化完生命周期,事件,但是数据代理还没有开始,此时无法访问数据和方法;
- created:初始化完数据监测和数据代理,此时可以访问到data中数据和方法;
- beforeMount:页面呈现未经vue编译的DOM结构,(vue已经开始解析模板,生成虚拟DOM,但页面中是未解析的内容)
- mounted:vue将内存中虚拟DOM转为真实DOM插入页面(vue使用
e
l
存
放
已
经
解
析
好
的
模
板
,
在
这
一
步
的
时
候
,
将
外
部
的
e
l
替
换
为
内
存
中
的
el存放已经解析好的模板,在这一步的时候,将外部的el替换为内存中的
el存放已经解析好的模板,在这一步的时候,将外部的el替换为内存中的el)在此时初始化过程结束,一般在此时开启定时器,发送网络请求,订阅消息,绑定事件等操作;
- beforeUpdate:此时,数据是更新后的,但是页面上的数据还没来得及更新,是旧的;
- updated:此时数据和页面都是新数据,两者保持同步了;
- beforeDestroy:vm中的data,methods,都处于可以使用状态,马上执行销毁过程,在此阶段会关闭定时器,取消订阅消息,解绑自定义事件;如果修改数据也不会触发更新了;
- destroyed:销毁完后;
- vm.$destroy():完全销毁一个实例,清理它与其它实例的连接,解绑它的全部指令及事件监听(这里是指自定义事件,原生斯事件并不会被销毁)一般不用;