Home  >  Article  >  Web Front-end  >  Detailed explanation of vue+update() usage

Detailed explanation of vue+update() usage

php中世界最好的语言
php中世界最好的语言Original
2018-06-13 11:04:3620159browse

This time I will bring you a detailed explanation of the use of vue update(), and what are the precautions for using vue update(). The following is a practical case, let's take a look.

Preface

Three months ago I read the vue source code to analyze how to achieve responsive data. The name of the article is vue source code for responsive data. Final analysis After the data changes, the update() method of Watcher will be called. So let’s continue to see what we have done after three months. (I have done a project with react-native in the past three months, and I have no intention of summarizing it, because it seems too complicated. Simple).

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

Purpose

Only by clarifying 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 in this direction. The goal is to find the answer starting from the entry of vue source code.

Start from the previous conclusion

Let’s review the previous conclusion first:

When vue is constructed, data (and Observer object is created on some other fields), getter and setter are intercepted, getter triggers dependency collection, and setter triggers notify.

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

Then here is the registration Rendering-related Watcher starts.

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

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

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)
}

So, it is the $mount() method that calls mountComponent(), (or specifying the el field during vue construction will 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 finally different dists cannot be published (this problem is left to study vue later) The whole process).

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
}

This code actually only does 3 things:

  • Call the beforeMount hook

  • Create Watcher

  • Calling mounted hook

(Hahaha) Then the core is to establish Watcher .

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

Looked at isRenderWatcher in Watcher:

if (isRenderWatcher) {
  vm._watcher = this
 }

Yes, I just made a copy to judge something when the watcher patches for the first time (from the comments, I still don’t know what it is for).

Then there is only one problem that remains unresolved, which is what updateComponent is.

updateComponent

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

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

Then Just look for vm._update() and vm._render().

I 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
 }
}

This method does it :

  • Generate VNode based on the render method of the current vm. (The render method may be compiled from the template or vue file, so it is inferred 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, then Put it in your own .parent attribute.

  • Finally return VNode

So the core is this sentence:

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

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

先看vm._renderProxy: 是initMixin()的时候设置的, 在生产环境返回vm, 开发环境返回代理, 那么我们认为他是一个可以debug的vm(就是vm), 细节之后再看.

vm.$createElement的代码在vdom文件夹下, 看了下是一个方法, 返回值一个VNode.

render有点复杂, 能不能以后研究, 总之就是把template或者vue单文件和mount目标parse成render函数.

小总结: vm._render()的返回值是VNode, 根据当前vm的render函数

接下来看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.
 }

我们关心的部分其实就是__patch()的部分, __patch()做了对dom的操作, 在_update()里判断了是否是初次调用, 如果是的话创建新dom, 不是的话传入新旧node进行比较再操作.

结论

vue的视图渲染是一种特殊的Watcher, watch的内容是一个函数, 函数运行的过程调用了render函数, render又是由template或者el的dom编译成的(template中含有一些被observe的数据). 所以template中被observe的数据有变化触发Watcher的update()方法就会重新渲染视图.

遗留

render函数是在哪里被编译的
vue源码发布时引入不同平台最后打成dist的流程是什么
__patch__和VNode的分析

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

小程序开发分享页面后返回首页

vue-cli axios请求与跨域

The above is the detailed content of Detailed explanation of vue+update() usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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