In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on the process of creating advanced applications of Vue 3.0. interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Vue 3.0 advanced application creation method process" it!
Next, we will start with a simple example and analyze the process of creating Vue 3.0 applications step by step from scratch.
Const {createApp, h} = Vue const app = createApp ({/ / ① data () {return {name:'I'm Brother Po'}}, template: 'Hello, {{name}}! `}) app.mount (' # app') / / ②
In the above code, we first create the app object through the createApp function, and then call the app.mount method to perform the application mount operation. When the above code runs successfully, Hello everyone will be displayed on the page. I am Brother Po, as shown in the following figure:
For the above example, it consists of two main steps: creating an app object and applying a mount. Here we will only analyze the process of creating app objects, while the process of applying mounts will be covered in the next article.
First, create an app object
First of all, Po uses the Performance tab of the Chrome developer tool to record the main process of creating app objects:
From the figure, we see the related functions involved in the process of creating the app object. In order to give you a visual understanding of the process of creating app objects, Po drew a picture:
After getting an overview of the main process, let's start with the entry point of createApp. Next, open the Chrome developer tool and add a breakpoint at createApp:
Through the breakpoint, we find the createApp function, which is called and returns an application instance that provides the application context. The entire component tree mounted by the application instance shares the same context. The createApp function is defined in the runtime-dom/src/index.ts file:
/ / packages/runtime-dom/src/index.ts export const createApp = ((... args) = > {const app = ensureRenderer (). CreateApp (... args) const {mount} = app app.mount = (containerOrSelector: Element | ShadowRoot | string): any = > {/ / omit the processing logic inside mount} return app}) as CreateAppFunction
Within createApp, the ensureRenderer function is called first, and the internal code of the function is simple:
/ / packages/runtime-dom/src/index.ts function ensureRenderer () {return renderer | | (renderer = createRenderer (rendererOptions))}
There is a delay in creating the renderer in the above code, so why do you do so? We found the answer from the comments in the runtime-dom/src/index.ts file:
/ / lazy create the renderer-this makes core renderer logic tree-shakable / / in case the user only imports reactivity utilities from Vue.
For our example, the renderer is needed, so the createRenderer function is called to create the renderer. Before we analyze the createRenderer function, let's analyze its parameter rendererOptions:
/ / packages/runtime-dom/src/index.ts export const extend = Object.assign const rendererOptions = extend ({patchProp, forcePatchProp}, nodeOps)
As you can see from the above code, the parameter rendererOptions is an object containing properties such as patchProp, forcePatchProp, and so on, where nodeOps is an abbreviation for node operations. For the Web browser environment, it defines the API for manipulating nodes / elements, such as creating elements, creating text nodes, inserting elements, and deleting elements. Because the source code for Vue 3.0 is written in TypeScript, you can find the type definition of the rendererOptions parameter in the source code:
/ / packages/runtime-core/src/renderer.ts export interface RendererOptions
< HostNode = RendererNode, HostElement = RendererElement >{patchProp (el: HostElement, key: string, prevValue: any, nextValue: any,...): void forcePatchProp? (el: HostElement, key: string): boolean insert (el: HostNode, parent: HostElement, anchor?: HostNode | null): void remove (el: HostNode): void createElement (type: string, isSVG?: boolean, isCustomizedBuiltIn?: string): HostElement createText (text: string): HostNode createComment (text: string): HostNode setText (HostNode setText: node, node: HostNode): HostNode (node: HostNode: HostNode): HostNode Text: string): void parentNode (node: HostNode): HostElement | null nextSibling (node: HostNode): HostNode | null querySelector? (selector: string): HostElement | null setScopeId? (el: HostElement, id: string): void cloneNode? (node: HostNode): HostNode insertStaticContent? (content: string, parent: HostElement,...): HostElement []}
All the methods related to the renderer are defined in the RendererOptions interface, which is intended to provide a layer of abstraction to the renderer. Developers can implement a custom renderer according to their own needs when meeting the constraints of the interface. After understanding the rendererOptions parameters, let's introduce the createRenderer function:
/ / packages/runtime-core/src/renderer.ts export interface RendererNode {[key: string]: any / / Index signature} export interface RendererElement extends RendererNode {} export function createRenderer
< HostNode = RendererNode, HostElement = RendererElement >(options: RendererOptions) {return baseCreateRenderer (options)}
The baseCreateRenderer function will be called inside the createRenderer function to execute the logic of creating the renderer. The logic inside the function is complicated. Let's take a look at the result returned after calling this function:
/ / packages/runtime-core/src/renderer.ts function baseCreateRenderer (options: RendererOptions, createHydrationFns?: typeof createHydrationFunctions): any {/ / omit most of the code return {render, hydrate, createApp: createAppAPI (render, hydrate)}}
In the above code, we finally see the long-awaited createApp property, whose value is the result of calling the createAppAPI function. Friends who have read brother Po's previous article should be familiar with the createAppAPI function, which is defined in the runtime-core/src/apiCreateApp.ts file:
/ packages/runtime-core/src/apiCreateApp.ts export function createAppAPI (render: RootRenderFunction, hydrate?: RootHydrateFunction): CreateAppFunction {return function createApp (rootComponent, rootProps = null) {const context = createAppContext () const installedPlugins = new Set () let isMounted = false const app: App = (context.app = {_ uid: uid++, _ component: rootComponent as ConcreteComponent, _ context: context / / omit use, mixin, unmount and provide methods component (name: string, component?: Component): any {/ /...}, directive (name: string, directive?: Directive) {/ /...}, mount (rootContainer: HostElement, isHydrate?: boolean): any {/ /...},}) return app}}
As can be seen from the above code, the createApp method supports two parameters, rootComponent and rootProps. After calling this method, an app object is returned, which provides multiple application API for the developer, such as the component method for registering or retrieving global components, the directive method for registering or retrieving global instructions, and the mount method for mounting the root component of the application instance to the specified DOM element.
In addition, in the body of the createApp function, we see the line const context = createAppContext (). As the name implies, the createAppContext function is used to create context objects related to the current application. So what does the so-called context object look like? To figure this out, let's take a look at the implementation of the createAppContext function:
/ / packages/runtime-core/src/apiCreateApp.ts export function createAppContext (): AppContext {return {app: null as any, config: {...}, mixins: [], components: {}, directives: {}, provides: Object.create (null)}}
After introducing the app and context objects, let's move on to analyzing the remaining logic code of the createApp function:
/ / packages/runtime-dom/src/index.ts export const createApp = ((... args) = > {const app = ensureRenderer (). CreateApp (... args) const {mount} = app app.mount = (containerOrSelector: Element | ShadowRoot | string): any = > {/ / omit the processing logic inside mount} return app}) as CreateAppFunction
From the above code, after the app object is created, the created app object is not returned immediately, but the app.mount property is overridden:
/ / packages/runtime-dom/src/index.ts export const createApp = ((... args) = > {const app = ensureRenderer (). CreateApp (... args) const {mount} = app app.mount = (containerOrSelector: Element | ShadowRoot | string): any = > {const container = normalizeContainer (containerOrSelector) / / supports both string and DOM object if (! container) return const component = app._component / / if the root component is not a function object and render and template properties are not set Then use the container's innerHTML as the template content if (! isFunction (component) & &! component.render & &! component.template) {component.template = container [XSS _ clean]} container [XSS _ clean] ='/ / empty the container content const proxy = mount (container) / / perform the mount operation if (container instanceof Element) {container.removeAttribute (') VMurcloak') / / avoid situations where the network is not good or the data load is too large The Mustache tag container.setAttribute ('data-v-app',')} return proxy} return app}) as CreateAppFunction appears during page rendering
Inside the app.mount method, when the information about the root component is set, the original mount method of the app object is called to perform the mount operation:
/ / packages/runtime-core/src/apiCreateApp.ts export function createAppAPI (render: RootRenderFunction, hydrate?: RootHydrateFunction): CreateAppFunction {return function createApp (rootComponent, rootProps = null) {const context = createAppContext () const installedPlugins = new Set () let isMounted = false / / identify whether const app: App = (context.app = {_ uid: uid++, _ component: rootComponent as ConcreteComponent, _ props: rootProps, _ context: context Mount (rootContainer: HostElement, isHydrate?: boolean): any {if (! isMounted) {/ / create the corresponding VNode node const vnode = createVNode (rootComponent as ConcreteComponent) based on the root component and root component attributes RootProps) vnode.appContext = context / / Application context if (isHydrate & & hydrate) {/ / related to server rendering hydrate (vnode as VNode, rootContainer as any)} else {/ / render vnode to the root container render (vnode RootContainer)} isMounted = true / / set the mounted status app._container = rootContainer return vnode.principent.proxy}},}) return app}}
So why override the app.mount method? The reason is that in order to support cross-platform, the app.mount methods defined in the runtime-dom package are related to the Web platform. In addition, in the runtime-dom package, a renderer for the Web platform is created for that platform. That is, when creating the renderer, the DOM-related API is encapsulated in the nodeOps object used:
/ / packages/runtime-dom/src/nodeOps.ts export const nodeOps: Omit = {/ / omit part of the method createElement: (tag, isSVG, is): Element = > isSVG? Doc.createElementNS (svgNS, tag): doc.createElement (tag, is? {is}: undefined), createText: text = > doc.createTextNode (text), createComment: text = > doc.createComment (text), querySelector: selector = > doc.querySelector (selector),}
Now that the main functions involved in the process of creating app objects have been introduced, partners who do not understand this process can refer to the diagram drawn by Brother Po, and then break point to debug the process of creating app objects.
Brother Po has something to say
2.1 what API is provided by the App object?
In Vue 3, the API that changes the global Vue behavior is now moved to the application instance created by the new createApp method. Application examples provide us with the following API to implement specific functions:
Config (): the object to which the configuration is applied.
Unmount (): uninstall the root component of the application instance on the supplied DOM element.
Mixin (mixin: ComponentOptions): apply a mixin to the entire scope of application.
Provide (key, value): sets a value that can be injected into all components within the scope of the application.
Component (name: string, component?: Component): registers or retrieves global components.
Directive (name: string, directive?: Directive): register or retrieve global directives.
Use (plugin: Plugin,... options: any []): installs the Vue.js plug-in, which will be installed only once when this method is called multiple times on the same plug-in.
Mount (rootContainer: HostElement, isHydrate?: boolean,isSVG?: boolean): mounts the root component of the application instance on the provided DOM element.
2.2 can you create multiple Vue applications using the createApp function?
Through the createApp function, we can easily create multiple Vue applications. The context of each application is isolated from each other, and the specific usage is as follows:
Const {createApp, h} = Vue const appA = createApp ({template: "I am Application A"}) const appB = createApp ({template: "I am Application B"}) appA.mount ('# appA') appB.mount ('# appB') so far, I believe you have a deeper understanding of "Vue 3.0 advanced application creation method process", might as well come to the actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.