初始化应用实例
-
创建 Vue 实例对象
createApp
中做了两件事:- 创建 app 对象
- 保存并重写 mount
/** * 创建 Vue 实例对象 */ const createApp = ((...args) => { // 1、创建 app 对象,延时创建渲染器,优点是当用户只依赖响应式包的时候,可以通过 tree-shaking 移除核心渲染逻辑相关的代码,减少体积 const app = ensureRenderer().createApp(...args) // 2、保存并重写 mount const { mount } = app app.mount = (containerOrSelector) => { // ... } return app })
为什么需要重写
mount
方法,而不把相关逻辑放在 app 对象的 mount 方法内部来实现呢?答:因为 Vue 不仅仅是为 Web 平台服务,它的目标是支持跨平台渲染,
createApp
函数内部的app.mount
方法是一个标准的可跨平台的组件渲染流程,因此需要根据具体场景进行定制化。 -
使用
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、创建根组件的 vnode const vnode = createVNode(rootComponent, rootProps) // 2、利用渲染器渲染 vnode render(vnode, rootContainer) // 3、设置应用实例的容器为根组件的容器 app._container = rootContainer return vnode.component.proxy } } return app } }
-
重写
app.mount
方法/** * 重写 app.mount 方法 * 重写的目的: * 1、让用户可以更灵活的使用 API * 2、兼容 Vue2 的写法 */ app.mount = (containerOrSelector) => { // 1、标准化容器,可以传字符串选择器或 DOM 对象,如果传的是字符串选择器则会将其转换为 DOM 对象作为最终挂载的容器 const container = normalizeContainer(containerOrSelector) if (!container) return const 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) }