/* Vue实例化对象创建之前 */
beforeCreate:Vue实例化对象创建之前,获取不到data里面的数据的
created:Vue实例化对象创建之后,可以获取data里面的数据,不可以获取到dom包括根节点
<div id="app">
<h1>{{msg}}</h1>
</div>
<script src="./vue.min.js"></script>
<script>
new Vue({
el: "#app",
data: {
msg: "前端工作"
},
// 最先执行的函数
beforeCreate: function () {
console.log("vue实例化对象创建之前");
// console.log(this.msg);
},
created() {
console.log("vue实例化对象创建之后");
console.log(this.msg);
console.log(document.querySelector("#app"));
// created 在生命周期里面不可能获取节点
console.log(this.$el);
// ⭐一般用来获取接口数据,速度更快,因为这个时候已经获取到data的数据了
setTimeout(() => {
this.msg = "从接口获取的数据"
}, 100)
},
beforeMount() {
// beforeMount 在生命周期里面可获取节点,但是不能显示出data数据
console.log('beforeMount', this.$el);
},
mounted() {
// ⭐操作元素节点的时候,写在mounted
console.log('mounted', this.$el);
}
})
</script>
/* Vue的dom挂载之前 */
beforeMount:dom挂载之前可以获取到根节点,还没有把data中的数据渲染到dom节点上
mounted:已经把data中的数据渲染到了dom节点上
beforeMount() {
// beforeMount 在生命周期里面可获取节点,但是不能显示出data数据
console.log('beforeMount', this.$el);
},
mounted() {
// 操作元素节点的时候,写在mounted
console.log('mounted', this.$el);
this.id = setInterval(() => {
this.num++;
console.log(this.num);
}, 1000)
},
/* 当把Vue实例中的data中的值改变了会触发beforeUpdate和updated */
beforeUpdate:在生命周期里面可获取节点,但是不能显示出data数据
updated:操作元素节点的时候,写在mounted
// 在data更新之前执行
beforeUpdate() {
console.log('beforeUpdate', this.msg, this.$el);
},
updated() {
console.log('beforeUpdate', this.msg, this.$el);
},
/* Vue组件销毁前 */
beforeDestroy:在调用$destroy()方法的时候 会执行下面的两个钩子函数
destroyed:/* ★beforeDestroy和destroyed的一个使用场景是在销毁定时器节约内存的时候都可以使用 */
beforeDestroy() {
clearInterval(this.id)
console.log('beforeDistory', this.msg, this.$el);
},
destroyed() {
// clearInterval(this.id)
console.log('destory', this.msg, this.$el);
},
methods: {
changeFn() {
this.msg = "111111111111111111"
},
destroyFn() {
this.$destroy()
}
}