Home Web Front-end JS Tutorial Vue data control view source code analysis

Vue data control view source code analysis

May 28, 2018 pm 04:49 PM
Source code view parse

This article provides you with a detailed analysis of the source code of the vue data control view and key annotations. Friends who are interested can refer to it for reference.

Analyze how vue implements data changes and updates views.

Preface

I read the vue source code three months ago to analyze it How to achieve responsive data? The name of the article is Responsive Data in Vue Source Code. Finally, it is analyzed that the update() method of Watcher will be called after the data changes. So let’s continue to see what update() does after three months. (I have done a project using react-native in the past three months, but I have no intention of summarizing it because it seems too simple).

The narrative method of this article is to follow the logic of looking at the source code. , the version of vue viewed is 2.5.2. I forked a source code to record comments.

Purpose

Only by clearing the direction of investigation can we reach the goal. , let’s talk about the target behavior first: what method is executed to update the view after the data changes. Then prepare to start looking for the answer starting from the entrance of the vue source code in this direction.

Start from the previous conclusion

First review the previous conclusions:

When vue is constructed, an Observer object will be created on data (and some other fields), the getter and setter are intercepted, and the getter triggers dependencies Collection, setter triggers notify.

The other object is Watcher. When registering watch, the watch object will be called once, which triggers the getter of the watch object and collects the dependencies into the deps of the current Watcher. When any dep's setter is triggered, it will notify the current Watcher to call the Watcher's update() method.

Then here we start by registering the rendering-related Watcher.

The file is found In src/core/instance/lifecycle.js.

new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */)
Copy after login

##mountComponent

Rendering related Watcher is called in the mountComponent() method, so let’s search where this method is called. There are only two places, namely src/platforms/web/runtime/index.js and src/platforms/weex/runtime/ index.js, taking web as an example:

Vue.prototype.$mount = function (
 el?: string | Element,
 hydrating?: boolean
): Component {
 el = el && inBrowser ? query(el) : undefined
 return mountComponent(this, el, hydrating)
}
Copy after login

It turns out that the $mount() method calls mountComponent(), (or specified during vue construction The el field will also automatically call the $mount() method), because the rendering objects of web and weex (what is weex? I have introduced it in other articles before) are different, so different files should be introduced when publishing, and the final publishing will not be different. dist (this problem is left to study the entire process of vue later).

The following is the mountComponent method:

export function mountComponent (
 vm: Component,
 el: ?Element,
 hydrating?: boolean
): Component {
 vm.$el = el // 放一份el到自己的属性里
 if (!vm.$options.render) { // render应该经过处理了, 因为我们经常都是用template或者vue文件
 // 判断是否存在render函数, 如果没有就把render函数写成空VNode来避免红错, 并报出黄错
 vm.$options.render = createEmptyVNode
 if (process.env.NODE_ENV !== 'production') {
  /* istanbul ignore if */
  if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
  vm.$options.el || el) {
  warn(
   'You are using the runtime-only build of Vue where the template ' +
   'compiler is not available. Either pre-compile the templates into ' +
   'render functions, or use the compiler-included build.',
   vm
  )
  } else {
  warn(
   'Failed to mount component: template or render function not defined.',
   vm
  )
  }
 }
 }
 callHook(vm, 'beforeMount')

 let updateComponent
 /* istanbul ignore if */
 if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
 // 不看这里的代码了, 直接看else里的, 行为是一样的
 updateComponent = () => {
  const name = vm._name
  const id = vm._uid
  const startTag = `vue-perf-start:${id}`
  const endTag = `vue-perf-end:${id}`

  mark(startTag)
  const vnode = vm._render()
  mark(endTag)
  measure(`vue ${name} render`, startTag, endTag)

  mark(startTag)
  vm._update(vnode, hydrating)
  mark(endTag)
  measure(`vue ${name} patch`, startTag, endTag)
 }
 } else {
 updateComponent = () => {
  vm._update(vm._render(), hydrating)
 }
 }

 // we set this to vm._watcher inside the watcher's constructor
 // since the watcher's initial patch may call $forceUpdate (e.g. inside child
 // component's mounted hook), which relies on vm._watcher being already defined
 // 注册一个Watcher
 new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */)
 hydrating = false

 // manually mounted instance, call mounted on self
 // mounted is called for render-created child components in its inserted hook
 if (vm.$vnode == null) {
 vm._isMounted = true
 callHook(vm, 'mounted')
 }
 return vm
}
Copy after login

This code is actually Only did 3 things:

  • Call the beforeMount hook

  • Create Watcher

  • Call mounted Hook

(Hahaha)The core is actually to create a Watcher.

Look at the parameters of the Watcher: vm is this, updateComponent is a function, noop is empty, null means empty, true means RenderWatcher.

Looked at isRenderWatcher in Watcher:

if (isRenderWatcher) {
  vm._watcher = this
 }
Copy after login

Yes, I just copied it for use Let's judge something when the watcher patches for the first time (from the comments, I still don't know what it does).

The only problem that remains unresolved is what updateComponent is.

updateComponent

If function is passed as the second parameter of Watcher's constructor, then this function becomes the getter of watcher. If you are smart, you should have guessed So, in this updateComponent, the getters of all the data in the view must be called, so that dependencies can be established in the watcher so that the view can respond to data changes.

updateComponent = () => {
  vm._update(vm._render(), hydrating)
 }
Copy after login

Then go find vm._update() and vm._render().

Found the ._render() method in src/core/instance/render.js.

Vue.prototype._render = function (): VNode {
 const vm: Component = this
 const { render, _parentVnode } = vm.$options // todo: render和_parentVnode的由来

 // reset _rendered flag on slots for duplicate slot check
 if (process.env.NODE_ENV !== 'production') {
  for (const key in vm.$slots) {
  // $flow-disable-line
  vm.$slots[key]._rendered = false
  }
 }

 if (_parentVnode) {
  vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject
 }

 // set parent vnode. this allows render functions to have access
 // to the data on the placeholder node.
 vm.$vnode = _parentVnode
 // render self
 let vnode
 try {
  vnode = render.call(vm._renderProxy, vm.$createElement)
 } catch (e) {
  // catch其实不需要看了, 都是做异常处理, _vnode是在vm._update的时候保存的, 也就是上次的状态或是null(init的时候给的)
  handleError(e, vm, `render`)
  // return error render result,
  // or previous vnode to prevent render error causing blank component
  /* istanbul ignore else */
  if (process.env.NODE_ENV !== 'production') {
  if (vm.$options.renderError) {
   try {
   vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
   } catch (e) {
   handleError(e, vm, `renderError`)
   vnode = vm._vnode
   }
  } else {
   vnode = vm._vnode
  }
  } else {
  vnode = vm._vnode
  }
 }
 // return empty vnode in case the render function errored out
 if (!(vnode instanceof VNode)) {
  if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
  warn(
   'Multiple root nodes returned from render function. Render function ' +
   'should return a single root node.',
   vm
  )
  }
  vnode = createEmptyVNode()
 }
 // set parent
 vnode.parent = _parentVnode
 return vnode
 }
}
Copy after login

This method does:

  • Generate VNode based on the render method of the current vm. (The render method may be compiled based on the template or vue file, Therefore, it is deduced that writing the render method directly is the most efficient)

  • If there is a problem with the render method, first call the renderError method, and if it fails, read the last vnode or null.

  • If there is a parent node, put it in its own .parent attribute.

  • Finally return VNode

So The core is this sentence:

vnode = render.call(vm._renderProxy, vm.$createElement)
Copy after login

I don’t know what render(), vm._renderProxy, vm.$createElement are.

Let’s look at vm._renderProxy first: it is set during initMixin(). It returns vm in the production environment and returns the proxy in the development environment. Then we think it is a vm that can be debugged (that is, vm). We will look at the details later.

# The code of ##vm.$createElement is in the vdom folder. After looking at it, it is a method that returns a VNode.

render is a bit complicated. Is it possible to study it later? In short, it is to combine the template or vue single file with The mount target is parsed into a render function.

Small summary: The return value of vm._render() is VNode, based on the render function of the current vm

Let’s look at vm._update()

Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
 const vm: Component = this
 if (vm._isMounted) {
  callHook(vm, 'beforeUpdate')
 }
 // 记录update之前的状态
 const prevEl = vm.$el
 const prevVnode = vm._vnode
 const prevActiveInstance = activeInstance
 activeInstance = vm
 vm._vnode = vnode
 // Vue.prototype.__patch__ is injected in entry points
 // based on the rendering backend used.
 if (!prevVnode) { // 初次加载, 只有_update方法更新vm._vnode, 初始化是null
  // initial render
  vm.$el = vm.__patch__( // patch创建新dom
  vm.$el, vnode, hydrating, false /* removeOnly */,
  vm.$options._parentElm,
  vm.$options._refElm
  )
  // no need for the ref nodes after initial patch
  // this prevents keeping a detached DOM tree in memory (#5851)
  vm.$options._parentElm = vm.$options._refElm = null
 } else {
  // updates
  vm.$el = vm.__patch__(prevVnode, vnode) // patch更新dom
 }
 activeInstance = prevActiveInstance
 // update __vue__ reference
 if (prevEl) {
  prevEl.__vue__ = null
 }
 if (vm.$el) {
  vm.$el.__vue__ = vm
 }
 // if parent is an HOC, update its $el as well
 if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
  vm.$parent.$el = vm.$el
 }
 // updated hook is called by the scheduler to ensure that children are
 // updated in a parent's updated hook.
 }
Copy after login

The part we care about is actually the __patch() part. __patch() does the operation on the dom and determines whether it is the first time in _update() Call, if yes, create a new dom, if not, pass in the old and new nodes for comparison and then operate.

Conclusion

Vue's view rendering is a special kind of Watcher. The content of the watch is a function. The render function is called during the running process of the function. The render is compiled by the template or el's dom (the template contains some observed objects). data). Therefore, changes in the observed data in the template trigger the Watcher's update() method to re-render the view.

Legacy

Where is the render function compiled?
What is the process of introducing different platforms when vue source code is released and finally typing it into dist
Analysis of __patch__ and VNode

The above is what I compiled for everyone. I hope It will be helpful to everyone in the future.

Related articles:

Methods for ajax cross-domain (same basic domain name) form submission

Implementing ajax images based on firefox Upload

Ajax loading external page pop-up layer effect implementation method

##

The above is the detailed content of Vue data control view source code analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A deep dive into the meaning and usage of HTTP status code 460 A deep dive into the meaning and usage of HTTP status code 460 Feb 18, 2024 pm 08:29 PM

In-depth analysis of the role and application scenarios of HTTP status code 460 HTTP status code is a very important part of web development and is used to indicate the communication status between the client and the server. Among them, HTTP status code 460 is a relatively special status code. This article will deeply analyze its role and application scenarios. Definition of HTTP status code 460 The specific definition of HTTP status code 460 is "ClientClosedRequest", which means that the client closes the request. This status code is mainly used to indicate

iBatis and MyBatis: Comparison and Advantage Analysis iBatis and MyBatis: Comparison and Advantage Analysis Feb 18, 2024 pm 01:53 PM

iBatis and MyBatis: Differences and Advantages Analysis Introduction: In Java development, persistence is a common requirement, and iBatis and MyBatis are two widely used persistence frameworks. While they have many similarities, there are also some key differences and advantages. This article will provide readers with a more comprehensive understanding through a detailed analysis of the features, usage, and sample code of these two frameworks. 1. iBatis features: iBatis is an older persistence framework that uses SQL mapping files.

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

What are the views in Word? What are the views in Word? Mar 19, 2024 pm 06:10 PM

I guess that many students want to learn the typesetting skills of Word, but the editor secretly tells you that before learning the typesetting skills, you need to understand the word views clearly. In Word2007, 5 views are provided for users to choose. These 5 views include pages. View, reading layout view, web layout view, outline view and normal view, let’s learn about these 5 word views with the editor today. 1. Page view Page view can display the appearance of the print result of the Word2007 document, which mainly includes headers, footers, graphic objects, column settings, page margins and other elements. It is the page view closest to the print result. 2. Reading layout view Reading layout view displays Word2007 documents and Office in the column style of a book

How to display the source code of PHP code in the browser without being interpreted and executed? How to display the source code of PHP code in the browser without being interpreted and executed? Mar 11, 2024 am 10:54 AM

How to display the source code of PHP code in the browser without being interpreted and executed? PHP is a server-side scripting language commonly used to develop dynamic web pages. When a PHP file is requested on the server, the server interprets and executes the PHP code in it and sends the final HTML content to the browser for display. However, sometimes we want to display the source code of the PHP file directly in the browser instead of being executed. This article will introduce how to display the source code of PHP code in the browser without being interpreted and executed. In PHP, you can use

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

See all articles