手写Vue2核心原理(二)

文章详细阐述了Vue框架中Mixin的实现原理,通过`mergeOptions`函数合并组件的选项,特别是生命周期钩子(HOOKS)的处理。在合并过程中,对各个生命周期函数使用策略模式进行合并。最后,展示了如何在实例初始化时调用这些生命周期钩子,以及`_init`方法在其中的作用。

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

生命周期的合并

源码地址:gitee源码地址

1.Mixin原理

import { mergeOptions } from '../utils/index';

export function initGlobalApi(Vue) {
    //> 源码:Vue.options = {created:[a,b,c],watch:[a,b,c]}
    Vue.options = {};
    Vue.Mixin = function (mixin) {
        // 对象的合并
        this.options = mergeOptions(this.options, mixin);
    };
}

2.合并生命周期

export const HOOKS = ['beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed'];
export function mergeOptions(parent, child) {
    //> Vue.options = {created:[a,b,c],watch:[a,b,c]}
    const options = {};

    let starts = {};
    starts.data = function (parentVal, childVal) {
        return childVal;
    };
    starts.watch = function () {};
    starts.methods = function () {};
    starts.computed = function () {};

    // 遍历生命周期
    HOOKS.forEach((key) => {
        starts[key] = mergeHooks;
    });

    function mergeHooks(parentVal, childVal) {
        //> 判断是否有父或子
        if (childVal) {
            if (parentVal) {
                return parentVal.concat(childVal);
            }
            return [childVal];
        } else {
            return [parentVal];
        }
    }
    for (const key in parent) {
        mergeField(key);
    }
    for (const key in child) {
        mergeField(key);
    }
    function mergeField(key) {
        // 根据key 采用策略模式
        if (starts[key]) {
            options[key] = starts[key](parent[key], child[key]);
        } else {
            options[key] = child[key];
        }
    }
    return options;
}

4.调用生命周期

export function callHook(vm, hook) {
    const handlers = vm.$options[hook];
    if (handlers) {
        for (let i = 0; i < handlers.length; i++) {
            handlers[i].call(vm);
        }
    }
}

5.初始化流程中调用生命周期

Vue.prototype._init = function (options) {
    const vm = this;
    vm.$options = mergeOptions(vm.constructor.options,options);
    // 初始化状态
    callHook(vm,'beforeCreate');
    initState(vm);
    callHook(vm,'created');
    if (vm.$options.el) {
    	vm.$mount(vm.$options.el);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龟中的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值