vue生命周期

本文详细解读Vue.js的四个关键生命周期阶段:实例创建(beforeCreate, created)、数据挂载(beforeMount, mounted)、数据更新(beforeUpdate, updated)和实例销毁(beforeDestroy, destroyed)。通过实例代码演示了每个阶段如何工作,以及何时能访问DOM和数据状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue生命周期

在这里插入图片描述

1.实例创建

beforecreate()实例创建之前
created()实例创建后

<template>
  <div ref="tdiv">
  {{message}}
 </div>
</template>

<script>
export default {
  data () {
    return {
		message:'hello world'
    }
  },
  methods: {
	changeMsg () {
                this.message = 'goodbye world'
            }
  },
  beforeCreate () {
			console.log('------初始化前------')
            console.log(this.message)
            console.log(this.$refs.tdiv)
  },
  created(){
  console.log('------初始化完成------')
            console.log(this.message)
            console.log(this.$refs.tdiv)

}
</script>

运行上面的代码我们获取的是
------初始化前------
undefined
undefined
------初始化完成------
hello world
undefined

证明了在beforeCreate()中 vue实例未创建 this不能使用 页面DOM也不能获取
在created()中实例创建完 可以获取data的数据 但是仍然不能获取页面DOM元素

2.数据挂载

beforeMount ()数据挂载之前
mounted() 数据挂载之后

<template>
  <div @click="changeMsg" ref="tdiv">
  {{message}}
 </div>
</template>

<script>
export default {
  data () {
    return {
		message:'hello world'
    }
  },
  methods: {
	changeMsg () {
                this.message = 'goodbye world'
            }
  },
  beforeMount () {
            console.log('------挂载前---------')
            console.log(this.message)
            console.log(this.$refs.tdiv)
        },
        mounted () {
            console.log('------挂载完成---------')
            console.log(this.message)
            console.log(this.$refs.tdiv)
        },

</script>

运行上面的代码我们获取的是
------挂载前------
hello world

<div @click="changeMsg" ref="tdiv">
  {{message}}
 </div>

------挂载完成------
hello world

<div>
 hello world
 </div>

在挂载前和挂载后的打印中 我们能明显发现 他们的主要区别在于页面元素是否渲染

3.数据更新

beforeUpdate(更新前)

updated(更新后)

当 data 变化时,会触发beforeUpdate方法 。data 数据尚未和最新的数据保持同步。

当数据页面和 data 数据已经保持同步了 ,会触发 updated 方法。

两个钩子函数最明显的变化是在视图更新上

4.实例销毁

beforeDestory(销毁前)

destoryed(销毁后)

组件销毁之前调用 ,在这一步,实例仍然完全可用。

组件销毁之后调用,对 data 的改变不会再触发周期函数,vue 实例已解除事件监听和 dom绑定,但 dom 结构依然存在。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值