Vue——生命周期

import Vue from 'vue'

const app=new Vue({
  el: '#root',
  //没有的话,使用render,继续没有,就把el的outerHTML编译成模板
  //template: '<div>{{text}} temp</div>',
  data: {
    text: 0
  },
  beforeCreate () {
    console.log(this.$el, 'beforeCreate')
  },
  created () {
    console.log(this.$el, 'created')
  },
  //$el是原来的el
  beforeMount () {
    console.log(this.$el, 'beforeMount')
  },
  //渲染函数
  render(h){
    //throw new TypeError(" render error")
    console.log('render')
    return h('div',{},this.text)
  } ,
  //模板已经挂载到el上,覆盖了el
  mounted () {
    console.log(this.$el, 'mounted')
  },
  //数据更新时
  beforeUpdate () {
    console.log(this, 'beforeUpdate')
  },
  updated() {
    console.log(this, 'updated')
  },
  activated () {
    console.log(this, 'activated')
  },
  deactivated () {
    console.log(this, 'deactivated')
  },
  beforeDestroy () {
    console.log(this, 'beforeDestroy')
  },
  destroyed () {
    console.log(this, 'destroyed')
  },

  //开发环境&&本组件的渲染error,才会被调用
  renderError(h,err){
    return h('div',{},err.stack)
  },
  //正式环境,会向上冒泡,子组件也可捕获
  errorCaptured(){

  }
})

// setInterval(()=>{
//   app.text=app.text+1
// },1000)

// setTimeout(()=>{
//   app.$destroy()
// },1000)
### Vue 生命周期常见面试题整理 #### 什么是 Vue 实例的生命周期Vue 实例从创建到销毁的过程被称为其生命周期。在此期间,它会经历一系列阶段,包括实例的创建、数据初始化、模板编译、DOM 挂载、渲染更新以及最终的卸载[^2]。 #### Vue 生命周期分为哪些主要阶段? Vue生命周期通常被划分为以下几个主要阶段: 1. **创建 (Creation)**:`beforeCreate` 和 `created`。 2. **挂载 (Mounting)**:`beforeMount` 和 `mounted`。 3. **更新 (Updating)**:`beforeUpdate` 和 `updated`。 4. **销毁 (Destruction)**:`beforeDestroy` 和 `destroyed`(在 Vue 3 中已更名为 `beforeUnmount` 和 `unmounted`)。 这些阶段中的每个钩子函数都提供了特定的时间点来执行自定义逻辑。 #### beforeMount 和 mounted 的区别是什么? - 在 `beforeMount` 阶段,尽管 Vue 已经完成了模板的编译并准备好了虚拟 DOM,但由于尚未真正挂载到实际的 DOM 上,因此无法访问真实的 DOM 节点[^4]。 - 到达 `mounted` 阶段时,组件已经被成功挂载到了页面上,此时可以通过 `$el` 访问到真实 DOM 元素。 #### updated 和 beforeUpdate 的作用分别是什么? - 当检测到数据变化触发重新渲染流程之前,会调用 `beforeUpdate` 方法,在这里可以获取旧状态下的 DOM 结构。 - 组件完成重新渲染之后,则进入 `updated` 阶段,此阶段适合处理一些依赖于最新 DOM 状态的任务,比如第三方插件集成或者手动操作 DOM。 #### 如何理解 keep-alive 对生命周期的影响? 当使用 `<keep-alive>` 缓存动态组件时,新增加了两个额外的生命周期钩子——`activated` 和 `deactivated`。它们会在组件激活或停用时触发,而不是像正常情况那样走完整的销毁重建流程。 ```javascript // 示例代码展示如何监听 activated/deactivated <template> <div v-if="show"> <component :is="currentComponent" /> </div> </template> <script> export default { data() { return { show: true, currentComponent: 'ChildA' }; }, }; </script> <!-- 子组件 --> <template> <p>我是子组件 A/B</p> </template> <script> export default { activated() { console.log('组件已被缓存并再次显示'); }, deactivated() { console.log('组件即将隐藏但仍保持缓存'); } } </script> ``` #### Vuex 是否影响 Vue 生命周期Vuex 主要用于全局状态管理,并不会直接影响 Vue生命周期方法本身。然而需要注意的是,在 Vuex 的 mutations 中不允许存在任何异步操作,因为这违背了 Flux 架构的设计原则之一即同步性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值