vue3源码学习api-createApp-amount

这篇具有很好参考价值的文章主要介绍了vue3源码学习api-createApp-amount。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

vue3 地址 https://github.com/vuejs/core

首先看看vue文档什么是 Vue?


Vue (发音为 /vjuː/,类似 view) 是一款用于构建用户界面的 JavaScript 框架。它基于标准 HTML、CSS 和 JavaScript 构建,并提供了一套声明式的、组件化的编程模型,帮助你高效地开发用户界面。无论是简单还是复杂的界面,Vue 都可以胜任。

下面是一个最基本的示例:

import { createApp, ref } from 'vue'

createApp({
  setup() {
    return {
      count: ref(0)
    }
  }
}).mount('#app')

学习vue 开发 都是从这个例子开始学习,在这个例子中涉及了这些api

  • 1 createApp
  • 2 mount
  • 3 ref
  • 4 setup

其中 ref 属于reactivity:反应系统 就暂时先不深究了

setup 属于vue3 新的语法糖 也先不深究了
就先看看最简单的createApp 和mount

createApp

先看看vue 仓库中的packages/vue/src/index.ts
地址 https://github.com/vuejs/core/blob/main/packages/vue/src/index.ts

export { compileToFunction as compile }
export * from '@vue/runtime-dom'

可以看到到处了一个编译的方法 和 @vue/runtime-dom 中的方法
根据上文
runtime-dom:针对浏览器的运行时。包括原生 DOM API、属性、属性、事件处理程序等的处理。
在runtime-dom 包中找到相关的方法
地址 https://github.com/vuejs/core/blob/main/packages/runtime-dom/src/index.ts

export const createApp = ((...args) => {
  const app = ensureRenderer().createApp(...args)

  if (__DEV__) {
    injectNativeTagCheck(app)
    injectCompilerOptionsCheck(app)
  }

  const { mount } = app
  app.mount = (containerOrSelector: Element | ShadowRoot | string): any => {
    const container = normalizeContainer(containerOrSelector)
    if (!container) return

    const component = app._component
    if (!isFunction(component) && !component.render && !component.template) {
      // __UNSAFE__
      // Reason: potential execution of JS expressions in in-DOM template.
      // The user must make sure the in-DOM template is trusted. If it's
      // rendered by the server, the template should not contain any user data.
      component.template = container.innerHTML
      // 2.x compat check
      if (__COMPAT__ && __DEV__) {
        for (let i = 0; i < container.attributes.length; i++) {
          const attr = container.attributes[i]
          if (attr.name !== 'v-cloak' && /^(v-|:|@)/.test(attr.name)) {
            compatUtils.warnDeprecation(
              DeprecationTypes.GLOBAL_MOUNT_CONTAINER,
              null
            )
            break
          }
        }
      }
    }

    // clear content before mounting
    container.innerHTML = ''
    const proxy = mount(container, false, container instanceof SVGElement)
    if (container instanceof Element) {
      container.removeAttribute('v-cloak')
      container.setAttribute('data-v-app', '')
    }
    return proxy
  }

  return app
}) as CreateAppFunction<Element>


function ensureRenderer() {
  return (
    renderer ||
    (renderer = createRenderer<Node, Element | ShadowRoot>(rendererOptions))
  )
}

走查代码可以发现 选是创建了一个渲染器Renderer
然后调用了渲染器的方法 createApp
查看具体方法

地址 https://github.com/vuejs/core/blob/main/packages/runtime-core/src/renderer.ts

创建渲染器的方法是一个比较长的方法
里面的很多方法看名称,更多的设计对dom的操作,不过我们还是先关注createApp 干了些什么

function baseCreateRenderer(
  options: RendererOptions,
  createHydrationFns?: typeof createHydrationFunctions
): any {
    ......
  return {
    render,
    hydrate,
    createApp: createAppAPI(render, hydrate)
  }
}

发现createAppAPI 来自apiCreateApp 文件

地址 https://github.com/vuejs/core/blob/main/packages/runtime-core/src/apiCreateApp.ts

import { createAppAPI, CreateAppFunction } from './apiCreateApp'

代码如下

export function createAppAPI<HostElement>(
  render: RootRenderFunction<HostElement>,
  hydrate?: RootHydrateFunction
): CreateAppFunction<HostElement> {
  return function createApp(rootComponent, rootProps = null) {
    if (!isFunction(rootComponent)) {
      rootComponent = extend({}, rootComponent)
    }

    if (rootProps != null && !isObject(rootProps)) {
      __DEV__ && warn(`root props passed to app.mount() must be an object.`)
      rootProps = null
    }

    const context = createAppContext()

    // TODO remove in 3.4
    if (__DEV__) {
      Object.defineProperty(context.config, 'unwrapInjectedRef', {
        get() {
          return true
        },
        set() {
          warn(
            `app.config.unwrapInjectedRef has been deprecated. ` +
              `3.3 now always unwraps injected refs in Options API.`
          )
        }
      })
    }

    const installedPlugins = new WeakSet()

    let isMounted = false

    const app: App = (context.app = {
      _uid: uid++,
      _component: rootComponent as ConcreteComponent,
      _props: rootProps,
      _container: null,
      _context: context,
      _instance: null,

      version,

      get config() {
        return context.config
      },

      set config(v) {
        if (__DEV__) {
          warn(
            `app.config cannot be replaced. Modify individual options instead.`
          )
        }
      },

      use(plugin: Plugin, ...options: any[]) {
        if (installedPlugins.has(plugin)) {
          __DEV__ && warn(`Plugin has already been applied to target app.`)
        } else if (plugin && isFunction(plugin.install)) {
          installedPlugins.add(plugin)
          plugin.install(app, ...options)
        } else if (isFunction(plugin)) {
          installedPlugins.add(plugin)
          plugin(app, ...options)
        } else if (__DEV__) {
          warn(
            `A plugin must either be a function or an object with an "install" ` +
              `function.`
          )
        }
        return app
      },

      mixin(mixin: ComponentOptions) {
        if (__FEATURE_OPTIONS_API__) {
          if (!context.mixins.includes(mixin)) {
            context.mixins.push(mixin)
          } else if (__DEV__) {
            warn(
              'Mixin has already been applied to target app' +
                (mixin.name ? `: ${mixin.name}` : '')
            )
          }
        } else if (__DEV__) {
          warn('Mixins are only available in builds supporting Options API')
        }
        return app
      },

      component(name: string, component?: Component): any {
        if (__DEV__) {
          validateComponentName(name, context.config)
        }
        if (!component) {
          return context.components[name]
        }
        if (__DEV__ && context.components[name]) {
          warn(`Component "${name}" has already been registered in target app.`)
        }
        context.components[name] = component
        return app
      },

      directive(name: string, directive?: Directive) {
        if (__DEV__) {
          validateDirectiveName(name)
        }

        if (!directive) {
          return context.directives[name] as any
        }
        if (__DEV__ && context.directives[name]) {
          warn(`Directive "${name}" has already been registered in target app.`)
        }
        context.directives[name] = directive
        return app
      },

      mount(
        rootContainer: HostElement,
        isHydrate?: boolean,
        isSVG?: boolean
      ): any {
        if (!isMounted) {
          // #5571
          if (__DEV__ && (rootContainer as any).__vue_app__) {
            warn(
              `There is already an app instance mounted on the host container.\n` +
                ` If you want to mount another app on the same host container,` +
                ` you need to unmount the previous app by calling \`app.unmount()\` first.`
            )
          }
          const vnode = createVNode(rootComponent, rootProps)
          // store app context on the root VNode.
          // this will be set on the root instance on initial mount.
          vnode.appContext = context

          // HMR root reload
          if (__DEV__) {
            context.reload = () => {
              render(cloneVNode(vnode), rootContainer, isSVG)
            }
          }

          if (isHydrate && hydrate) {
            hydrate(vnode as VNode<Node, Element>, rootContainer as any)
          } else {
            render(vnode, rootContainer, isSVG)
          }
          isMounted = true
          app._container = rootContainer
          // for devtools and telemetry
          ;(rootContainer as any).__vue_app__ = app

          if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
            app._instance = vnode.component
            devtoolsInitApp(app, version)
          }

          return getExposeProxy(vnode.component!) || vnode.component!.proxy
        } else if (__DEV__) {
          warn(
            `App has already been mounted.\n` +
              `If you want to remount the same app, move your app creation logic ` +
              `into a factory function and create fresh app instances for each ` +
              `mount - e.g. \`const createMyApp = () => createApp(App)\``
          )
        }
      },

      unmount() {
        if (isMounted) {
          render(null, app._container)
          if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
            app._instance = null
            devtoolsUnmountApp(app)
          }
          delete app._container.__vue_app__
        } else if (__DEV__) {
          warn(`Cannot unmount an app that is not mounted.`)
        }
      },

      provide(key, value) {
        if (__DEV__ && (key as string | symbol) in context.provides) {
          warn(
            `App already provides property with key "${String(key)}". ` +
              `It will be overwritten with the new value.`
          )
        }

        context.provides[key as string | symbol] = value

        return app
      },

      runWithContext(fn) {
        currentApp = app
        try {
          return fn()
        } finally {
          currentApp = null
        }
      }
    })

    if (__COMPAT__) {
      installAppCompatProperties(app, context, render)
    }

    return app
  }
}

可以发现createApp 的第一个参数是rootComponent
需要传递的是一个组件,作为根组件
第二个参数rootProps是这个给这个组件传递的参数

通过走查 文件可以发现一些常用的api 也是出现在这里
例如 use、mixin、component、directive、mount、unmount、provide

我们要找的mount 也是对这里mount的调用

mount

可以看到 mount主要是参数是rootContainer 另外两个是可选参数
在通过createVNode 创建一个vnode 之后
调用getExposeProxy
返回当前刚才创建的vnode的代理

export function getExposeProxy(instance: ComponentInternalInstance) {
  if (instance.exposed) {
    return (
      instance.exposeProxy ||
      (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
        get(target, key: string) {
          if (key in target) {
            return target[key]
          } else if (key in publicPropertiesMap) {
            return publicPropertiesMap[key](instance)
          }
        },
        has(target, key: string) {
          return key in target || key in publicPropertiesMap
        }
      }))
    )
  }
}

代码中实际调用的mount

依然在createAppAPI 里面 这里的传参更友好 了可以传入Selector 方便选择dom节点文章来源地址https://www.toymoban.com/news/detail-741802.html

app.mount = (containerOrSelector: Element | ShadowRoot | string): any => {
    const container = normalizeContainer(containerOrSelector)
    if (!container) return

    const component = app._component
    if (!isFunction(component) && !component.render && !component.template) {
      // __UNSAFE__
      // Reason: potential execution of JS expressions in in-DOM template.
      // The user must make sure the in-DOM template is trusted. If it's
      // rendered by the server, the template should not contain any user data.
      component.template = container.innerHTML
      // 2.x compat check
      if (__COMPAT__ && __DEV__) {
        for (let i = 0; i < container.attributes.length; i++) {
          const attr = container.attributes[i]
          if (attr.name !== 'v-cloak' && /^(v-|:|@)/.test(attr.name)) {
            compatUtils.warnDeprecation(
              DeprecationTypes.GLOBAL_MOUNT_CONTAINER,
              null
            )
            break
          }
        }
      }
    }

    // clear content before mounting
    container.innerHTML = ''
    const proxy = mount(container, false, container instanceof SVGElement)
    if (container instanceof Element) {
      container.removeAttribute('v-cloak')
      container.setAttribute('data-v-app', '')
    }
    return proxy
  }

到了这里,关于vue3源码学习api-createApp-amount的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 【Vue2.0源码学习】全局API篇-Vue中全局API分析

    与实例方法不同,实例方法是将方法挂载到 Vue 的原型上,而全局API是直接在 Vue 上挂载方法。在 Vue 中,全局API一共有12个,分别是 Vue.extend 、 Vue.nextTick 、 Vue.set 、 Vue.delete 、 Vue.directive 、 Vue.filter 、 Vue.component 、 Vue.use 、 Vue.mixin 、 Vue.observable 、 Vue.version 。这12个API中有的

    2024年02月08日
    浏览(45)
  • Vue3的手脚架使用和组件父子间通信-插槽(Options API)学习笔记

    全局安装最新vue3 升级Vue CLI: 如果是比较旧的版本,可以通过下面命令来升级 通过脚手架创建项目 父组件 子组件 UserComponent.vue 父组件 **子组件1 JiaComponent.vue ** ** 子组件2 JianComponent.vue ** 父组件 子组件 TitleComponents.vue 父组件 **子组件 NavComponent.vue ** 父组件 子组件 NavCompone

    2024年02月05日
    浏览(31)
  • Vue3 —— watch 监听器及源码学习

    该文章是在学习 小满vue3 课程的随堂记录 示例均采用 script setup ,且包含 typescript 的基础用法 在 vue3 中,必须是 ref 、 reactive 包裹起来的数据,才可以被 watch 监听到 1、语法: watch(source, cb, options) source 是监听的目标,有 4 种书写形式: reactive 形式的响应式数据 ref 形式的响

    2024年02月12日
    浏览(12)
  • 【学习笔记】Vue3源码解析:第五部分 - 实现渲染(2)

    【学习笔记】Vue3源码解析:第五部分 - 实现渲染(2)

    课程地址:【已完结】全网最详细Vue3源码解析!(一行行带你手写Vue3源码) 第五部分-:(对应课程的第33 - 35节) 第33节:《讲解组件渲染流程》 1、在 render 函数中拿到虚拟dom vnode后,编写patch函数,它接收3个参数:null、vnode、container,分别代表:上一次的虚拟dom即旧的虚

    2024年04月23日
    浏览(12)
  • 【Vue3】如何创建Vue3项目及组合式API

    【Vue3】如何创建Vue3项目及组合式API

    文章目录 前言 一、如何创建vue3项目? ①使用 vue-cli 创建  ②使用可视化ui创建  ③npm init vite-app   ④npm init vue@latest 二、 API 风格 2.1 选项式 API (Options API) 2.2 组合式 API (Composition API) 总结 例如:随着前端领域的不断发展,vue3学习这门技术也越来越重要,很多人都开启了学习

    2024年02月03日
    浏览(9)
  • 【Vue3】vue3中的watchEffect使用及其他的API

    【Vue3】vue3中的watchEffect使用及其他的API

    目录  一,watchEffect 二,生命周期 三,什么是hooks? 四,toRef  五,其他组合式API 5.1shallowReactiveshallowRef 5.2readonlyshallowReadonly 5.3.toRawmarkRaw 5.4自定义Ref-customRef ​5.5provide$inject 5.6响应式数据的判断 写在最后     1.watch: 既要指明监视的属性,也要指明监视的回调。 2.watchEffect: 不

    2024年02月01日
    浏览(11)
  • vue3 封装api接口

    新建axiosj.ts 新建状态码文件: 导出案例    export function login  (params) {      return request(\\\'/admin-api/system/auth/login\\\',params, \\\'post\\\')    } 使用  

    2024年02月16日
    浏览(13)
  • Vue3组合式API

    Vue3组合式API

    目录 composition API vs options API 体验 composition API setup 函数 reactive 函数 ref 函数 script setup 语法 计算属性 computed 函数 监听器 watch 函数 生命周期 模板中 ref 的使用 组件通讯 - 父传子 组件通讯 - 子传父 依赖注入 - provide 和 inject 保持响应式 - toRefs 函数 vue2 采用的就是 options API (

    2024年02月07日
    浏览(14)
  • vue3 快速入门系列 —— 其他API

    其他章节请看: vue3 快速入门 系列 前面我们已经学习了 vue3 的一些基础知识,本篇将继续讲解一些常用的 其他api ,以及较完整的分析vue2 和 vue3 的改变。 shallowRef shallow 中文:“浅层的” shallowRef:浅的 ref()。 先用 ref 写个例子: 这4个按钮都会触发页面数据的变化。 现在将

    2024年04月22日
    浏览(10)
  • vue3组合式API介绍

    根据官方的说法,vue3.0的变化包括性能上的改进、更小的 bundle 体积、对 TypeScript 更好的支持、用于处理大规模用例的全新 API,全新的api指的就是本文主要要说的组合式api。 在 vue3 版本之前,我们复用组件(或者提取和重用多个组件之间的逻辑),通常有以下几种方式: M

    2023年04月22日
    浏览(15)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包