Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of the Global API combed by Vue official documents

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of the overall API of Vue official documents. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Vue.extend

The configuration item data must be function, otherwise the configuration is invalid. The source code of data merging rules is as follows:

Pass in a non-function type of data (data is configured as {adata 1} in the figure above). When merging options, the development version issues a warning if data is not a function type, and then directly returns parentVal, which means that the data option passed in by extend is ignored.

We know that when instantiating Vue, data can be an object. Isn't the merge rule common here? Note that there is a judgment of if (! vm) above. Vm is valuable when instantiated, so it is different from Vue.extend. In fact, the following comments are also explained (in a Vue.extend merge, both should be function), which is why the official document says that data is a special case.

In addition, the official document says "subclass" because Vue.extend returns a function that "inherits" Vue. The source code structure is as follows:

Vue.extend = function (extendOptions) {/ / * var Super = this; var SuperId = Super.cid; / / * var Sub = function VueComponent (options) {this._init (options);}; Sub.prototype = Object.create (Super.prototype); Sub.prototype.constructor = Sub; / / * return Sub}

Vue.nextTick

Since you use vue, of course, you have to think along the data-driven way, the so-called data-driven, that is, do not directly operate all the operations of dom,dom can be completed using various instructions of vue, instructions to "bind" the data and dom, operating data can not only achieve dom updates, but also more convenient.

If the browser supports Promise, or uses the Promise library (but the exposed must be called Promise, because the judgment in the source code is typeof Promise! = = 'undefined'), nextTick returns the Promise object.

Vue.nextTick () .then (() = > {/ / do sth})

The callback for Vue to execute nextTick is cb.call (ctx) as call; ctx is the current Vue instance, so you can directly use this to call the instance configuration in the callback.

NextTick can be simply understood as putting the callback to the end for execution. If Promise and MutationObserver are not supported in the source code, setTimeout will be used to execute the callback. This is not the usual way to postpone code execution.

If (typeof Promise! = 'undefined' & & isNative (Promise)) {} else if (typeof MutationObserver! = =' undefined' & & (isNative (MutationObserver) | | / / PhantomJS and iOS 7.x MutationObserver.toString () ='[object MutationObserverConstructor]')) {} else {/ / fallback to setTimeout / * istanbul ignore next * / timerFunc = function () {setTimeout (nextTickHandler, 0);};}

For example, let's actually look at this:

{{a}} new Vue ({el:'# app', data: {a: 1}, mounted: function name (params) {console.log ('start'); this.$nextTick (function () {console.log (' beforeChange', this.$refs.dom.textContent)}) this.a = 2; console.log ('change') This.$nextTick (function () {console.log ('afterChange', this.$refs.dom.textContent)}) console.log (' end');}}) / / console print / / start// change// end// beforeChange 1max / afterChange 2

You may wonder why beforeChange outputs 1 instead of 2 since they are all executed last. This is because the dom update behind this.a=2 is also triggered by nextTick. The actual order of execution of the above code is: beforeChange > update dom > afterChange.

Vue.set

Vue.set (target, key, value), target cannot be the root data object of Vue instance or Vue instance, because the following judgment is made in the source code:

Var ob = (target). _ ob__;if (target._isVue | | (ob & & ob.vmCount)) {"development"! = = 'production' & & warn (' Avoid adding reactive properties to a Vue instance or its root $data'+'at runtime-declare it upfront in the data option.'); return val}

Target._isVue prevents attributes from being added to the Vue instance, and ob & & ob.vmCount prevents attributes from being added to the root data object of the Vue instance.

Vue.delete

If the Vue can detect the delete operation, then the api will not appear. If you must use delete to delete the attribute of $data, use Vue.delete, otherwise the update of dom will not be triggered.

Target with Vue.set,Vue.delete (target, key) cannot be the root data object of a Vue sample or Vue sample. The blocking method in the source code is the same as Vue.set.

In version 2.2.0 +, if target is an array, key is the array subscript. Because the Vue.delete delete array is actually deleted with splice, delete can be used to delete the array, but the location is still there, so it cannot be really deleted.

Var a = [1,2,3]; delete a [0]; console.log (a); / / [undefined, 2,3]

Vue.use

The Vue.use source code is relatively simple and can be posted entirely.

Vue.use = function (plugin) {var installedPlugins = (this._installedPlugins | (this._installedPlugins = [])); if (installedPlugins.indexOf (plugin) >-1) {return this} / / additional parameters var args = toArray (arguments, 1); args.unshift (this); if (typeof plugin.install = 'function') {plugin.install.apply (plugin, args);} else if (typeof plugin =' function') {plugin.apply (null, args) } installedPlugins.push (plugin); return this}

The installed plug-in is placed in installedPlugins, and before installing the plug-in, installedPlugins.indexOf (plugin) is used to determine whether the plug-in has been installed, thus preventing the same plug-in from registering multiple times.

The plug-in type is object, you must specify the install attribute to install the plug-in (typeof plugin.install = 'function'), and the plug-in execution uses plugin.install.apply (plugin, args);, so this accesses the other properties of the plug-in. Args here is passed in by Vue (args.unshift (this);) and Vue.use (toArray (arguments, 1), where 1 means to intercept from arguments [1]) except for plugin.

Vue.use ({a: 1, install: function (Vue) {console.log (this.a) / / 1 console.log (arguments) / / [function Vue (options), "a", "b", "c"]}},'a', 'baked,' c')

The plug-in type is function, and the installation calls plugin.apply (null, args);, so the plug-in runtime this is null in strict mode and Window in non-strict mode.

'use strict'Vue.use (function plugin () {console.log (this) / / null console.log (arguments) / / [function Vue (options), "a", "b", "c"]},' a', 'baked,' c')

Vue.compile

Like many JS template engines, the template is converted into a render function in advance, and Vue.compile is used to do this, with the goal of converting the template (template or el) into a render function.

Vue.compile returned {render:Function,staticRenderFns:Array}, render can be directly applied to the configuration item render of Vue, and how did staticRenderFns come from? and according to the example on the official website, Vue also has a hidden configuration item staticRenderFns. Let's take a look at the example.

Var compiled = Vue.compile ('+'no data binding' +'{{prop}}'+') console.log (compiled.render.toString ()) console.log (compiled.staticRenderFns.toString ()) / / renderfunction anonymous () {with (this) {return _ c ('div', [_ m (0), _ c (' section') [_ v (_ s (prop))])}} / / staticRenderFnsfunction anonymous () {with (this) {return _ c ('header', [_ c (' h _ 2), [_ v ("no data binding")]])}

Dom that is not originally bound to the data is put into the staticRenderFns and then called with _ m (0) in the render. However, this is not always the case. For example, when the above template is removed, the staticRenderFns header is put directly into the render function when the length of the header is 0.

Function anonymous () {with (this) {return _ c ('div', [_ c (' header', [_ v ("no data binding")]), _ c ('section', [_ v (_ s (prop))])])}}

The source code corresponding to Vue.compile is rather complex. The core judgment of the source code corresponding to the above rendering that is not put into staticRenderFns is as follows:

/ / For a node to qualify as a static root, it should have children that / / are not just static text. Otherwise the cost of hoisting out will / / outweigh the benefits and it's better off to just always render it fresh. If (node.static & & node.children.length & &! (node.children.length = 1 & & node.children [0] .type = 3)) {node.staticRoot = true; return} else {node.staticRoot = false;}

Does not meet the judgment condition! (node.children.length = 1 & & node.children [0] .type = 3), there is a child node TextNode (nodeType=3). The comment also shows that a node meets the criteria of a static root node.

In addition, the official website shows that this method is only effective when building independently. What is independent building? This official website has made a detailed introduction, I will not repeat it. Corresponding to the official website address: explanation of different builds.

Taking a closer look at the compiled render method is very different from the render method we wrote. However, it can still be configured directly to the render configuration options. So those inside _ c (), _ m (), _ v (), _ s () can be called? If you look at the _ _ proto__ of an instance of Vue, you will find:

/ / internal render helpers.// these are exposed on the instance prototype to reduce generated render// code size.Vue.prototype._o = markOnce;Vue.prototype._n = toNumber;Vue.prototype._s = toString;Vue.prototype._l = renderList;Vue.prototype._t = renderSlot;Vue.prototype._q = looseEqual;Vue.prototype._i = looseIndexOf;Vue.prototype._m = renderStatic;Vue.prototype._f = resolveFilter;Vue.prototype._k = checkKeyCodes;Vue.prototype._b = bindObjectProps;Vue.prototype._v = createTextVNode Vue.prototype._e = createEmptyVNode;Vue.prototype._u = resolveScopedSlots;Vue.prototype._g = bindObjectListeners

As noted in the notes, these methods are designed to reduce the volume of the generated render functions.

Global API leaves directive, filter, component and mixin, which are similar and correspond to configuration items, which will be described in more detail in "options".

This is the end of the article on "sample Analysis of the overall API of Vue official documents". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report