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

What are the methods worth learning in the Vue source code

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the methods worth learning in the Vue source code?" in the operation of the actual case, many people will encounter such a dilemma, then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

1. Data type judgment

The data returned by Object.prototype.toString.call () is of type [object Object], and then intercepts the 8th bit to the last bit with slice, and the result is Object.

Var _ toString = Object.prototype.toString; function toRawType (value) {return _ toString.call (value) .slice (8,-1)}

Run the result test

ToRawType ({}) / / Object toRawType ([]) / / Array toRawType (true) / / Boolean toRawType (undefined) / / Undefined toRawType (null) / / Null toRawType (function () {}) / / Function

two。 Using closures to construct map cached data

Vue to determine whether we write the component name is not html built-in tags, if we use the array class traversal then will loop many times to get the results, if the array into an object, the tag signature is set to the object's key, then do not have to traverse the search in turn, only need to search once to get the results, improving the search efficiency.

Function makeMap (str, expectsLowerCase) {/ / build closure set map var map = Object.create (null); var list = str.split (','); for (var I = 0; I

< list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } // 利用闭包,每次判断是否是内置标签只需调用isHTMLTag var isHTMLTag = makeMap('html,body,base,head,link,meta,style,title') console.log('res', isHTMLTag('body')) // true 3. 二维数组扁平化 vue中_createElement格式化传入的children的时候用到了simpleNormalizeChildren函数,原来是为了拍平数组,使二维数组扁平化,类似lodash中的flatten方法。 // 先看lodash中的flatten _.flatten([1, [2, [3, [4]], 5]]) // 得到结果为 [1, 2, [3, [4]], 5] // vue中 function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // es6中 等价于 function simpleNormalizeChildren (children) { return [].concat(...children) } 4. 方法拦截 vue中利用Object.defineProperty收集依赖,从而触发更新视图,但是数组却无法监测到数据的变化,但是为什么数组在使用push pop等方法的时候可以触发页面更新呢,那是因为vue内部拦截了这些方法。 // 重写push等方法,然后再把原型指回原方法 var ARRAY_METHOD = [ 'push', 'pop', 'shift', 'unshift', 'reverse', 'sort', 'splice' ]; var array_methods = Object.create(Array.prototype); ARRAY_METHOD.forEach(method =>

{array_ methods [method] = function () {/ / intercepted method console.log ('intercepted' + method + 'method is called for dependency collection); return Array.prototype [method] .apply (this, arguments);}})

Run the result test

Var arr = [1 unshift 2 3] arr.__proto__ = array_methods / / change the prototype of arr arr.unshift (6) / / print the result: the intercepted unshift method is called for dependency collection

5. Implementation of inheritance

The Vue.extend instantiation component is called in vue, Vue.extend is the VueComponent constructor, and VueComponent inherits Vue using Object.create, so there is not much difference between Vue and Vue.extend in normal development. Here we mainly learn to use es5 native methods to implement inheritance, and of course, class classes in es6 inherit directly from extends.

/ / inheritance method function inheritPrototype (Son, Father) {var prototype = Object.create (Father.prototype) prototype.constructor = Son / / assign Father.prototype to Son.prototype Son.prototype = prototype} function Father (name) {this.name = name this.arr = [1J 2m 3]} Father.prototype.getName = function () {console.log (this.name)} function Son (name, age) {Father.call (this) Name) this.age = age} inheritPrototype (Son, Father) Son.prototype.getAge = function () {console.log (this.age)}

Run the result test

Var son1 = new Son ("AAA", 23) son1.getName () / / AAA son1.getAge () / / 23 son1.arr.push (4) console.log (son1.arr) / / 1 var son2 3 var son2 = new Son ("BBB", 24) son2.getName () / / BBB son2.getAge () / / 24 console.log (son2.arr) / / 1 Magi 2L3

6. Execute once

The once method is relatively simple, so just use the closure to implement it.

Function once (fn) {var called = false; return function () {if (! called) {called = true; fn.apply (this, arguments);}

7. Shallow copy

Simple deep copy we can use JSON.stringify () to achieve, but the vue source code in the looseEqual shallow copy is also very interesting, first type judgment and then recursive call, overall is not difficult, learn some ideas.

Function looseEqual (a, b) {if (a = b) {return true} var isObjectisObjectA = isObject (a); var isObjectisObjectB = isObject (b); if (isObjectA & & isObjectB) {try {var isArrayA = Array.isArray (a); var isArrayB = Array.isArray (b) If (isArrayA & & isArrayB) {return a.length = b.length & & a.every (function (e, I) {return looseEqual (e, b [I])})} else if (! isArrayA & &! isArrayB) {var keysA = Object.keys (a); var keysB = Object.keys (b) Return keysA.length = = keysB.length & & keysA.every (function (key) {return looseEqual (a) B [key])})} else {/ * istanbul ignore next * / return false}} catch (e) {/ * istanbul ignore next * / return false}} else if (! isObjectA & &! isObjectB) {return String (a) = = String (b)} else {return false}} function isObject (obj) {return Obj! = = null & & typeof obj = = 'object'} "what are the methods worth learning in Vue source code?" that's it. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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