开发公司vue3的setup的使用和原理解析

1.前言

开发公司最近在做相关的项目,开发公司用到了组合式api,对于vue3开发公司的语法的改进也是大为赞赏,开发公司用起来十分方便。开发公司对于已经熟悉vue2开发公司写法的同学也说,开发公司上手还是需要一定的学习成本,开发公司有可能目前停留在会写开发公司会用的阶段,但是setup开发公司带来哪些改变,以及ref,reactive这两api开发公司内部实现原理到底是什么,开发公司下面先来总结:

setup开发公司开发公司带来的改变:

1.解决了的data和methods开发公司方法相距太远,开发公司无法组件之间复用

2.提供了script开发公司标签引入共同业务逻辑的代码块,顺序执行

3.script变成setup函数,开发公司默认暴露给模版

4.开发公司组件直接挂载,无需注册

5.开发公司自定义的指令也可以在开发公司模版中自动获得

6.this开发公司不再是这个活跃实例的引用

7.开发公司带来的大量全新api,比如,defineEmits,withDefault,toRef,toRefs

ref带来的改变:

Vue 开发公司提供了一个  开发公司方法来允许我们创建可以使用开发公司任何值类型开发公司的响应式数据

Ref作TS开发公司的类型标注

reactive带来的改变:

可以使用  函数创建一个响应式对象或数组

reactive可以隐式地从它的参数中推导类型

使用interface进行类型标注

需要了解vue2和vue3区别的可以查看我的这篇文章:

2.setup

在 setup() 函数中手动暴露大量的状态和方法非常繁琐。幸运的是,我们可以通过使用构建工具来简化该操作。当使用单文件组件(SFC)时,我们可以使用 <script setup> 来大幅度地简化代码。

<script setup> 中的顶层的导入和变量声明可在同一组件的模板中直接使用。你可以理解为模板中的表达式和 <script setup> 中的代码处在同一个作用域中。

里面的代码会被编译成组件 setup() 函数的内容。这意味着与普通的 <script> 只在组件被首次引入的时候执行一次不同,<script setup>中的代码会在每次组件实例被创建的时候执行。

官方解答: 

<script setup> 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的 <script> 语法,它具有更多优势:

  • 更少的样板内容,更简洁的代码。
  • 能够使用纯 TypeScript 声明 props 和自定义事件。
  • 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
  • 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。

setup执行是在创建实例之前就是beforeCreate执行,所以setup函数中的this还不是组件的实例,而是undefined,setup是同步的。

setup?: (this: void, props: Readonly<LooseRequired<Props & UnionToIntersection<ExtractOptionProp<Mixin>> & UnionToIntersection<ExtractOptionProp<Extends>>>>, ctx: SetupContext<E>) => Promise<RawBindings> | RawBindings | RenderFunction | void;)

 在上面的代码中我们了解到了第一个参数props,还有第二个参数context。

props是接受父组件传递过来的所有的属性和方法;context是一个对象,这个对象不是响应式的,可以进行解构赋值。存在属性为attrs:instance.slots,slots: instance.slots,emit: instance.emit。

  1. setup(props, { attrs, slots, emit, expose }) {
  2.    ...
  3.  }
  4.  或
  5.  setup(props, content) {
  6.    const { attrs, slots, emit, expose } = content
  7.  }

这里要注意一下,attrs 和 slots 是有状态的对象,它们总是会随组件本身的更新而更新。这意味着你应该避免对它们进行解构,并始终以 attrs.x 或 slots.x 的方式引用 property。请注意,与 props 不同,attrs 和 slots 的 property 是非响应式的。如果你打算根据 attrs 或 slots 的更改应用副作用,那么应该在 onBeforeUpdate 生命周期钩子中执行此操作。

3.源码分析

在vue的3.2.3x版本中,处理setup函数源码文件位于:node_moudles/@vue/runtime-core/dist/runtime-core.cjs.js文件中。

setupStatefulComponent

下面开始解析一下setupStatefulComponent的执行过程:

  1. function setupStatefulComponent(instance, isSSR) {
  2. var _a;
  3. const Component = instance.type;
  4. {
  5. if (Component.name) {
  6. validateComponentName(Component.name, instance.appContext.config);
  7. }
  8. if (Component.components) {
  9. const names = Object.keys(Component.components);
  10. for (let i = 0; i < names.length; i++) {
  11. validateComponentName(names[i], instance.appContext.config);
  12. }
  13. }
  14. if (Component.directives) {
  15. const names = Object.keys(Component.directives);
  16. for (let i = 0; i < names.length; i++) {
  17. validateDirectiveName(names[i]);
  18. }
  19. }
  20. if (Component.compilerOptions && isRuntimeOnly()) {
  21. warn(`"compilerOptions" is only supported when using a build of Vue that ` +
  22. `includes the runtime compiler. Since you are using a runtime-only ` +
  23. `build, the options should be passed via your build tool config instead.`);
  24. }
  25. }
  26. // 0. create render proxy property access cache
  27. instance.accessCache = Object.create(null);
  28. // 1. create public instance / render proxy
  29. // also mark it raw so it's never observed
  30. instance.proxy = reactivity.markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  31. {
  32. exposePropsOnRenderContext(instance);
  33. }
  34. // 2. call setup()
  35. const { setup } = Component;
  36. if (setup) {
  37. const setupContext = (instance.setupContext =
  38. setup.length > 1 ? createSetupContext(instance) : null);
  39. setCurrentInstance(instance);
  40. reactivity.pauseTracking();
  41. const setupResult = callWithErrorHandling(setup, instance, 0 /* ErrorCodes.SETUP_FUNCTION */, [reactivity.shallowReadonly(instance.props) , setupContext]);
  42. reactivity.resetTracking();
  43. unsetCurrentInstance();
  44. if (shared.isPromise(setupResult)) {
  45. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  46. if (isSSR) {
  47. // return the promise so server-renderer can wait on it
  48. return setupResult
  49. .then((resolvedResult) => {
  50. handleSetupResult(instance, resolvedResult, isSSR);
  51. })
  52. .catch(e => {
  53. handleError(e, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
  54. });
  55. }
  56. else {
  57. // async setup returned Promise.
  58. // bail here and wait for re-entry.
  59. instance.asyncDep = setupResult;
  60. if (!instance.suspense) {
  61. const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
  62. warn(`Component <${name}>: setup function returned a promise, but no ` +
  63. `<Suspense> boundary was found in the parent component tree. ` +
  64. `A component with async setup() must be nested in a <Suspense> ` +
  65. `in order to be rendered.`);
  66. }
  67. }
  68. }
  69. else {
  70. handleSetupResult(instance, setupResult, isSSR);
  71. }
  72. }
  73. else {
  74. finishComponentSetup(instance, isSSR);
  75. }
  76. }

函数接受两个参数,一个是组建实例,另一个是是否ssr渲染,接下来是验证过程,这里的文件是开发环境文件, DEV 环境,则会开始检测组件中的各种选项的命名,比如 name、components、directives 等,如果检测有问题,就会在开发环境报出警告。

检测完成之后,进行初始化,生成一个accessCached的属性对象,该属性用以缓存渲染器代理属性,以减少读取次数。然后在初始化一个代理的属性,instance.proxy = reactivity.markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));这个代理属性代理了组件的上下文,并且将它设置为观察原始值,这样这个代理对象将不会被追踪。

接下来便是setup的核心逻辑了,如果组件上有setup 函数,继续执行,如果不存在跳到尾部,执行finishComponentSetup(instance, isSSR),完成组件的初始化,否则就会进入 if (setup) 之后的分支条件中。是否执行setup生成上下文取决于setup.length > 1 ?createSetupContext(instance) : null。

来看一下setup执行上下文究竟有哪些东西:

  1. function createSetupContext(instance) {
  2. const expose = exposed => {
  3. if (instance.exposed) {
  4. warn(`expose() should be called only once per setup().`);
  5. }
  6. instance.exposed = exposed || {};
  7. };
  8. let attrs;
  9. {
  10. // We use getters in dev in case libs like test-utils overwrite instance
  11. // properties (overwrites should not be done in prod)
  12. return Object.freeze({
  13. get attrs() {
  14. return attrs || (attrs = createAttrsProxy(instance));
  15. },
  16. get slots() {
  17. return reactivity.shallowReadonly(instance.slots);
  18. },
  19. get emit() {
  20. return (event, ...args) => instance.emit(event, ...args);
  21. },
  22. expose
  23. });
  24. }
  25. }

 expose解析:

可以在 setup() 中使用该 API 来清除地控制哪些内容会明确地公开暴露给组件使用者。

当你在封装组件时,如果嫌 ref 中暴露的内容过多,不妨用 expose 来约束一下输出。

  1. import { ref } from 'vue'
  2. export default {
  3. setup(_, { expose }) {
  4. const count = ref(0)
  5. function increment() {
  6. count.value++
  7. }
  8. // 仅仅暴露 increment 给父组件
  9. expose({
  10. increment
  11. })
  12. return { increment, count }
  13. }
  14. }

例如当你像上方代码一样使用 expose 时,父组件获取的 ref 对象里只会有 increment 属性,而 count 属性将不会暴露出去。

执行setup函数 

在处理完 createSetupContext 的上下文后,组件会停止依赖收集,并且开始执行 setup 函数。

const setupResult = callWithErrorHandling(setup, instance, 0 /* ErrorCodes.SETUP_FUNCTION */, [reactivity.shallowReadonly(instance.props) , setupContext]); 

Vue 会通过 callWithErrorHandling 调用 setup 函数,组件实例instance传入,这里我们可以看最后一行,是作为 args 参数传入的,与上文描述一样,props 会始终传入,若是 setup.length <= 1 , setupContext 则为 null。

调用玩setup之后,会重置收集的状态,reactivity.resetTracking(),接下来是判断setupResult的类型。

  1. if (shared.isPromise(setupResult)) {
  2. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  3. if (isSSR) {
  4. // return the promise so server-renderer can wait on it
  5. return setupResult
  6. .then((resolvedResult) => {
  7. handleSetupResult(instance, resolvedResult, isSSR);
  8. })
  9. .catch(e => {
  10. handleError(e, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
  11. });
  12. }
  13. else {
  14. // async setup returned Promise.
  15. // bail here and wait for re-entry.
  16. instance.asyncDep = setupResult;
  17. if (!instance.suspense) {
  18. const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
  19. warn(`Component <${name}>: setup function returned a promise, but no ` +
  20. `<Suspense> boundary was found in the parent component tree. ` +
  21. `A component with async setup() must be nested in a <Suspense> ` +
  22. `in order to be rendered.`);
  23. }
  24. }
  25. }

如果 setup 函数的返回值是 promise 类型,并且是服务端渲染的,则会等待继续执行。否则就会报错,说当前版本的 Vue 并不支持 setup 返回 promise 对象。

如果不是 promise 类型返回值,则会通过 handleSetupResult 函数来处理返回结果。

  1. else {
  2. handleSetupResult(instance, setupResult, isSSR);
  3. }
  1. function handleSetupResult(instance, setupResult, isSSR) {
  2. if (shared.isFunction(setupResult)) {
  3. // setup returned an inline render function
  4. if (instance.type.__ssrInlineRender) {
  5. // when the function's name is `ssrRender` (compiled by SFC inline mode),
  6. // set it as ssrRender instead.
  7. instance.ssrRender = setupResult;
  8. }
  9. else {
  10. instance.render = setupResult;
  11. }
  12. }
  13. else if (shared.isObject(setupResult)) {
  14. if (isVNode(setupResult)) {
  15. warn(`setup() should not return VNodes directly - ` +
  16. `return a render function instead.`);
  17. }
  18. // setup returned bindings.
  19. // assuming a render function compiled from template is present.
  20. {
  21. instance.devtoolsRawSetupState = setupResult;
  22. }
  23. instance.setupState = reactivity.proxyRefs(setupResult);
  24. {
  25. exposeSetupStateOnRenderContext(instance);
  26. }
  27. }
  28. else if (setupResult !== undefined) {
  29. warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  30. }
  31. finishComponentSetup(instance, isSSR);
  32. }

 在 handleSetupResult 这个结果捕获函数中,首先判断 setup 返回结果的类型,如果是一个函数,并且又是服务端的行内模式渲染函数,则将该结果作为 ssrRender 属性;而在非服务端渲染的情况下,会直接当做 render 函数来处理。

接着会判断 setup 返回结果如果是对象,就会将这个对象转换成一个代理对象,并设置为组件实例的 setupState 属性。

最终还是会跟其他没有 setup 函数的组件一样,调用 finishComponentSetup 完成组件的创建。

finishComponentSetup

  1. function finishComponentSetup(instance, isSSR, skipOptions) {
  2. const Component = instance.type;
  3. // template / render function normalization
  4. // could be already set when returned from setup()
  5. if (!instance.render) {
  6. // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
  7. // is done by server-renderer
  8. if (!isSSR && compile && !Component.render) {
  9. const template = Component.template;
  10. if (template) {
  11. {
  12. startMeasure(instance, `compile`);
  13. }
  14. const { isCustomElement, compilerOptions } = instance.appContext.config;
  15. const { delimiters, compilerOptions: componentCompilerOptions } = Component;
  16. const finalCompilerOptions = shared.extend(shared.extend({
  17. isCustomElement,
  18. delimiters
  19. }, compilerOptions), componentCompilerOptions);
  20. Component.render = compile(template, finalCompilerOptions);
  21. {
  22. endMeasure(instance, `compile`);
  23. }
  24. }
  25. }
  26. instance.render = (Component.render || shared.NOOP);
  27. // for runtime-compiled render functions using `with` blocks, the render
  28. // proxy used needs a different `has` handler which is more performant and
  29. // also only allows a whitelist of globals to fallthrough.
  30. if (installWithProxy) {
  31. installWithProxy(instance);
  32. }
  33. }
  34. // support for 2.x options
  35. {
  36. setCurrentInstance(instance);
  37. reactivity.pauseTracking();
  38. applyOptions(instance);
  39. reactivity.resetTracking();
  40. unsetCurrentInstance();
  41. }
  42. // warn missing template/render
  43. // the runtime compilation of template in SSR is done by server-render
  44. if (!Component.render && instance.render === shared.NOOP && !isSSR) {
  45. /* istanbul ignore if */
  46. if (!compile && Component.template) {
  47. warn(`Component provided template option but ` +
  48. `runtime compilation is not supported in this build of Vue.` +
  49. (``) /* should not happen */);
  50. }
  51. else {
  52. warn(`Component is missing template or render function.`);
  53. }
  54. }
  55. }

这个函数的主要作用是获取并为组件设置渲染函数,对于模板(template)以及渲染函数的获取方式有以下三种规范行为:

1、渲染函数可能已经存在,通过 setup 返回了结果。例如我们在上一节讲的 setup 的返回值为函数的情况。

2、如果 setup 没有返回,则尝试获取组件模板并编译,从 Component.render 中获取渲染函数,

3、如果这个函数还是没有渲染函数,则将 instance.render 设置为空,以便它能从 mixins/extend 等方式中获取渲染函数。

这个在这种规范行为的指导下,首先判断了服务端渲染的情况,接着判断没有 instance.render 存在的情况,当进行这种判断时已经说明组件并没有从 setup 中获得渲染函数,在进行第二种行为的尝试。从组件中获取模板,设置好编译选项后调用Component.render = compile(template, finalCompilerOptions);进行编译,编译过程不再赘述。

最后将编译后的渲染函数赋值给组件实例的 render 属性,如果没有则赋值为 NOOP 空函数。

接着判断渲染函数是否是使用了 with 块包裹的运行时编译的渲染函数,如果是这种情况则会将渲染代理设置为一个不同的 has handler 代理陷阱,它的性能更强并且能够去避免检测一些全局变量。

至此组件的初始化完毕,渲染函数也设置结束了。

4.总结

在vue3中,新的setup函数属性给我们提供了书写的便利,其背后的工作量无疑是巨大的,有状态的组件的初始化的过程,在 setup 函数初始化部分我们讨论的源码的执行过程,我们不仅学习了 setup 上下文初始化的条件,也明确的知晓了 setup 上下文究竟给我们暴露了哪些属性,并且从中学到了一个新的 RFC 提案属性: expose 属性

我们学习了 setup 函数执行的过程以及 Vue 是如何处理捕获 setup 的返回结果的。

然后我们讲解了组件初始化时,不论是否使用 setup 都会执行的 finishComponentSetup 函数,通过这个函数内部的逻辑我们了解了一个组件在初始化完毕时,渲染函数设置的规则。

最后,如果本文对你了解setup过程有所帮助,希望三连支持一波哈~~~❤️

你也可以关注我的vue其他文章:

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发