Vue3 源码解读系列(二)——初始化应用实例

编程入门 行业动态 更新时间:2024-10-27 14:20:43

Vue3 源码解读系列(二)——<a href=https://www.elefans.com/category/jswz/34/1770206.html style=初始化应用实例"/>

Vue3 源码解读系列(二)——初始化应用实例

初始化应用实例

  1. 创建 Vue 实例对象

    createApp 中做了两件事:

    1. 创建 app 对象
    2. 保存并重写 mount
    /*** 创建 Vue 实例对象*/
    const createApp = ((...args) => {// 1、创建 app 对象,延时创建渲染器,优点是当用户只依赖响应式包的时候,可以通过 tree-shaking 移除核心渲染逻辑相关的代码,减少体积const app = ensureRenderer().createApp(...args)// 2、保存并重写 mountconst { mount } = appapp.mount = (containerOrSelector) => {// ...}return app
    })
    

    为什么需要重写 mount 方法,而不把相关逻辑放在 app 对象的 mount 方法内部来实现呢?

    答:因为 Vue 不仅仅是为 Web 平台服务,它的目标是支持跨平台渲染createApp 函数内部的 app.mount 方法是一个标准的可跨平台的组件渲染流程,因此需要根据具体场景进行定制化。

  2. 使用 ensureRenderer().createApp() 来创建 app 对象

    // 渲染相关的一些配置,比如:更新属性的方法,操作 DOM 的方法
    const rendererOptions = {patchProp,...nodeOps
    }let renderer
    /*** 检查是否存在渲染器*/
    function ensureRenderer() {return renderer || (renderer = createRenderer(rendererOptions))
    }
    /*** 创建渲染器*/
    function createRenderer(options) {return baseCreateRenderer(options)
    }
    /*** 创建渲染器的基本逻辑*/
    function baseCreateRenderer(options) {// 组件渲染的核心逻辑function render(vnode, container) {// ...}return {render,createApp: createAppAPI(render)}
    }
    /*** 创建应用实例的 API*/
    function createAppAPI(render) {// 创建应用实例,接收的两个参数:rootComponent - 根组件的对象 和 rootProps - props参数return function createApp(rootComponent, rootProps = null) {const app = {_component: rootComponent,_props: rootProps,// app.mount 组件挂载逻辑mount(rootContainer) {// 1、创建根组件的 vnodeconst vnode = createVNode(rootComponent, rootProps)// 2、利用渲染器渲染 vnoderender(vnode, rootContainer)// 3、设置应用实例的容器为根组件的容器app._container = rootContainerreturn vnodeponent.proxy}}return app}
    }
    
  3. 重写 app.mount 方法

    /*** 重写 app.mount 方法* 重写的目的:* 1、让用户可以更灵活的使用 API* 2、兼容 Vue2 的写法*/
    app.mount = (containerOrSelector) => {// 1、标准化容器,可以传字符串选择器或 DOM 对象,如果传的是字符串选择器则会将其转换为 DOM 对象作为最终挂载的容器const container = normalizeContainer(containerOrSelector)if (!container) returnconst component = app._component// 2、如果组件对象没有定义 render 函数和 template 模板,则取容器的 innerHTML 作为组件模板内容if (!isFunction(component) && !component.render && !component.template) {component.template = container.innerHTML}// 3、挂载前清空容器内容container.innerHTML = ''// 4、真正的挂载return mount(container)
    }
    

更多推荐

Vue3 源码解读系列(二)——初始化应用实例

本文发布于:2023-11-15 04:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593986.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   源码   应用实例   系列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!