Vue 生命周期

发布时间 2023-10-11 15:17:34作者: Binge-和时间做朋友

Vue 生命周期

Vue 生命周期指的是 Vue 实例从创建到销毁整个过程

Vue 生命周期函数

Vue 生命周期函数(或生命周期回调函数、生命周期钩子)指的是在 Vue 生命周期的特定关键时间点被 Vue 自动调用的一些特殊函数

注意事项
  • 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的
  • 生命周期函数中的 this 指向是 vm 或 组件实例对象

Vue 生命周期流程图

官网:

尚硅谷_前端技术_Vue全家桶

详细版:

生命周期

生命周期分析

1. 初始化显示
  • beforeCreate()
  • created()
  • beforeMount()
  • mounted()
2. 更新状态:this.xxx = value
  • beforeUpdate()
  • updated()
3. 销毁 Vue 实例 vm.$destory()
  • beforeDestroy()
  • destroyed()

常用的生命周期方法

1. mounted()

发送 ajax 请求,、启动定时器、绑定自定义事件、订阅消息等异步任务(初始化操作)

2. beforeDestroy()

做收尾工作, 如: 清除定时器、解绑自定义事件、取消订阅消息等(首尾工作)

销毁 Vue 实例注意事项

  1. 销毁后借助 Vue 开发者工具看不到任何信息
  2. 销毁后自定义事件会失效,但原生 DOM 事件依然有效
  3. 一般不会在 beforeDestroy 操作数据,因为即便操作数据,也不会再触发更新流程
案例代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>分析生命周期</title>
		<!-- 引入Vue -->
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器-->
		<div id="root" :x="n">
			<h2 v-text="n"></h2>
			<h2>当前的n值是:{{n}}</h2>
			<button @click="add">点我n+1</button>
			<button @click="bye">点我销毁vm</button>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		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变了')
				}
			},
			beforeCreate() {
				console.log('beforeCreate')
			},
			created() {
				console.log('created')
			},
			beforeMount() {
				console.log('beforeMount')
                  // debugger // 使用 debugger 语句类似于在代码中设置断点
			},
			mounted() {
				console.log('mounted')
			},
			beforeUpdate() {
				console.log('beforeUpdate')
			},
			updated() {
				console.log('updated')
			},
			beforeDestroy() {
				console.log('beforeDestroy')
			},
			destroyed() {
				console.log('destroyed')
			},
		})
	</script>
</html>