vue生命周期符合什么模式

今天分享一下面试中遇到的一个问题----vue生命周期符合什么模式???

Vue的生命周期通常符合了观察者模式

在Vue中,组件的生命周期包括创建、更新、销毁等过程。在这些过程中,Vue实例会触发一系列的生命周期钩子函数,以便开发者可以在关键时刻插入自己的逻辑。

观察者模式涉及一个主题(Subject)和多个观察者(Observer)

它们之间建立一种一对多的依赖关系。当主题的状态发生变化时,会通知所有依赖的观察者。主题会维护观察者对象列表,并在其状态发生改变时通知这些观察者。观察者则是实现了一个更新接口,可以在收到主题通知时得知状态变更。

在Vue中,组件的生命周期遵循以下过程:

  1. 创建(beforeCreate, Created)
  2. 挂载(beforeMount, Mounted)
  3. 更新(beforeUpdate, Updated)
  4. 销毁(beforeDestroy, Destroyed)

Vue组件的生命周期方法可以看作是观察者,它们会在对应的生命周期阶段被触发。当组件实例化,Vue根据组件的生命周期顺序依次执行相应的生命周期方法。这里是一个简化的例子:

class VueComponent {
  constructor() {
    this.observers = [];
  }

  registerObserver(observer) {
    this.observers.push(observer);
  }

  notifyObservers(lifecycleEvent) {
    this.observers.forEach((observer) => {
      if (typeof observer[lifecycleEvent] === 'function') {
        observer[lifecycleEvent]();
      }
    });
  }

  create() {
    this.notifyObservers('beforeCreate');
    console.log('Component Created');
    this.notifyObservers('created');
  }

  mount() {
    this.notifyObservers('beforeMount');
    console.log('Component Mounted');
    this.notifyObservers('mounted');
  }

  update() {
    this.notifyObservers('beforeUpdate');
    console.log('Component Updated');
    this.notifyObservers('updated');
  }

  destroy() {
    this.notifyObservers('beforeDestroy');
    console.log('Component Destroyed');
    this.notifyObservers('destroyed');
  }
}

const myObserver = {
  beforeCreate() {
    console.log('Observer: Before Component Created');
  },
  created() {
    console.log('Observer: Component Created');
  },
  beforeMount() {
    console.log('Observer: Before Component Mounted');
  },
  mounted() {
    console.log('Observer: Component Mounted');
  },
  beforeUpdate() {
    console.log('Observer: Before Component Updated');
  },
  updated() {
    console.log('Observer: Component Updated');
  },
  beforeDestroy() {
    console.log('Observer: Before Component Destroyed');
  },
  destroyed() {
    console.log('Observer: Component Destroyed');
  },
};

const myComponent = new VueComponent();
myComponent.registerObserver(myObserver);
myComponent.create();
myComponent.mount();
myComponent.update();
myComponent.destroy();

在这个例子中,VueComponent充当主题,myObserver是观察者。我们在VueComponent中创建了一个观察者数组,并提供了注册观察者的方法。当调用组件的createmountupdatedestroy方法时,VueComponent会根据当前生命周期阶段通知所有注册的观察者。

对于Vue来说,它并不是直接实现观察者模式,而是借助了这种模式的思想,让开发者可以在不同生命周期时机执行相关代码。这些生命周期方法就类似观察者,在合适的时机被调用。

以上是我的理解,各位大佬可以进行点评。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值