详细展示生命周期
调用方法和获取data中的数据 ,最早是在create方法中
在created方法中可以发送请求。
想要操作DOM元素,最早是在mounted之后
mounted之后,元素真正的挂载到了浏览器端。
不同生命周期可以做的事情
上面的图片详细解释了生命周期钩子里应该做哪些事情,诸位可以自行取舍,下面我们结合案例总结下:
- created钩子: 发ajax请求
- mounted钩子: 也可以发送ajax请求,更多的是操作DOM元素
- updated钩子: 可以用来监听路由变化
- beforeDestroy钩子: 记录当前页面的一些数据,清楚页面滚动事件
- destroy钩子: 清楚定时器等
深入理解生命周期
<template>
<div>
我是父组件
<son></son>
</div>
</template>
<script>
import son from "./components/son.vue"
export default {
components: {
son
},
data(){
return {}
},
beforeCreate(){
console.log("我是父组件的----beforeCreate钩子------")
},
created(){
console.log("我是父组件的----created钩子------")
},
beforeMount(){
console.log("我是父组件的----beforeMount钩子------")
},
mounted(){
console.log("我是父组件的----mounted钩子------")
},
beforeUpdate(){
console.log("我是父组件的----beforeUpdate钩子------")
},
update(){
console.log("我是父组件的----update钩子------")
},
beforeDestroy(){
console.log("我是父组件的----beforeDestroy钩子------")
},
destroyed(){
console.log("我是父组件的----destroy钩子------")
}
}
</script>
<style>
</style>
在生命周期的钩子函数中,不能使用箭头函数
因为箭头函数是没有this的,而在生命周期的钩子的函数中有this