


Let's talk about the 38 tool functions under the Vue3 shared module (source code reading)
Compared with the tool functions of
Vue2, the tool functions of
##Vue3
have changed a lot. My personal feeling is mainly reflected in the syntax. Fully embrace
es6; [Related recommendations:
vuejs video tutorial, web front-end development]
All tool functions
- makeMap
: Generate an object similar to
Set, use Used to determine whether a certain value exists
- EMPTY_OBJ
: Empty object
- EMPTY_ARR
: Empty array
- NOOP
: Empty function
- NO
: Function that returns
false - isOn
: Determine whether it is
on Events starting with - isModelListener
: Determine the string starting with
onUpdate - extend
: Merge objects
- remove
: Remove a value from the array
- hasOwn
: Determine whether the object has a certain attribute
- isArray
: Determines whether it is an array
- isMap
: Determines whether it is
Map ##isSet - : Determines whether it is an array
Set
isDate - : Determine whether it is
Date
isRegExp - : Determine whether it is
RegExp
isFunction - : Determine whether it is a function
- : Determine whether it is a string
- : Determine whether it is
Symbol
isObject - : Determine whether it is an object
- : Determine whether Is
Promise
objectToString - :
Object.prototype.toString
##toTypeString
: - Abbreviation of Object.prototype.toString
toRawType
: Get the type of object -
isPlainObject
: Determine whether it is a normal object -
isIntegerKey
: Determine whether it is an integer - key
isReservedProp
: Determine whether it is a reserved property -
isBuiltInDirective
: Determine whether it is a built-in instruction -
camelize
: Convert the string to camel case -
hyphenate
: Convert the string to concatenated case Characters -
capitalize
: Capitalize the first letter of the string -
toHandlerKey
: Convert the string to the - key
of the event handler
hasChanged
: Determine whether two values are equal -
invokeArrayFns
: Call the function in the array -
def
: Define the properties of the object -
looseToNumber
: Convert a string to a number -
toNumber
: Convert a string to a number -
getGlobalThis
: Get the global object -
genPropsAccessExp
: Generate the access expression of - props
this Most of them are the same as the tool functions of
Vue2
Vue2, this Quick reading;
If you want more details, you can read the article I wrote before:
[Source code reading] Analysis of 36 utility functions in the Vue2 source code shared module
And this time it is the direct source code, the ts
version, which is no longer processed intojs, so read the
ts source code directly;
Official start
makeMap
export function makeMap(
str: string,
expectsLowerCase?: boolean
): (key: string) => boolean {
const map: Record<string, boolean> = Object.create(null)
const list: Array<string> = str.split(',')
for (let i = 0; i < list.length; i++) {
map[list[i]] = true
}
return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]
}
makeMap
The source code is in the same directory as makeMap.ts file, directly use the
export keyword to export after importing it. The implementation method is the same as the implementation method of
Vue2;
EMPTY_OBJ & EMPTY_ARR
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__ ? Object.freeze({}) : {} export const EMPTY_ARR = __DEV__ ? Object.freeze([]) : []
EMPTY_OBJ
和EMPTY_ARR
的实现方式和Vue2
的emptyObject
相同,都是使用Object.freeze
冻结对象,防止对象被修改;
NOOP
export const NOOP = () => {}
和Vue2
的noop
实现方式相同,都是一个空函数,移除了入参;
NO
/** * Always return false. */ export const NO = () => false
和Vue2
的no
实现方式相同,都是一个返回false
的函数,移除了入参;
isOn
const onRE = /^on[^a-z]/ export const isOn = (key: string) => onRE.test(key)
判断是否是on
开头的事件,并且on
后面的第一个字符不是小写字母;
isModelListener
export const isModelListener = (key: string) => key.startsWith('onUpdate:')
判断是否是onUpdate:
开头的字符串;
参考:startWith
extend
export const extend = Object.assign
直接拥抱es6
的Object.assign
,Vue2
的实现方式是使用for in
循环;
remove
export const remove = <T>(arr: T[], el: T) => { const i = arr.indexOf(el) if (i > -1) { arr.splice(i, 1) } }
对比于Vue2
删除了一些代码,之前的快速删除最后一个元素的判断不见了;
猜测可能是因为有bug
,因为大家都知道Vue2
的数组响应式必须使用Array
的api
,那样操作可能会导致数组响应式失效;
hasOwn
const hasOwnProperty = Object.prototype.hasOwnProperty export const hasOwn = ( val: object, key: string | symbol ): key is keyof typeof val => hasOwnProperty.call(val, key)
使用的是Object.prototype.hasOwnProperty
,和Vue2
相同;
isArray
export const isArray = Array.isArray
使用的是Array.isArray
,和Vue2
相同;
isMap & isSet & isDate & isRegExp
export const isMap = (val: unknown): val is Map<any, any> => toTypeString(val) === '[object Map]' export const isSet = (val: unknown): val is Set<any> => toTypeString(val) === '[object Set]' export const isDate = (val: unknown): val is Date => toTypeString(val) === '[object Date]' export const isRegExp = (val: unknown): val is RegExp => toTypeString(val) === '[object RegExp]'
都是使用Object.toString
来判断类型,对比于Vue2
新增了isMap
和isSet
和isDate
,实现方式没变;
isFunction & isString & isSymbol & isObject
export const isFunction = (val: unknown): val is Function => typeof val === 'function' export const isString = (val: unknown): val is string => typeof val === 'string' export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol' export const isObject = (val: unknown): val is Record<any, any> => val !== null && typeof val === 'object'
和Vue2
的实现方式相同,都是使用typeof
来判断类型,新增了isSymbol
;
isPromise
export const isPromise = <T = any>(val: unknown): val is Promise<T> => { return isObject(val) && isFunction(val.then) && isFunction(val.catch) }
和Vue2
对比修改了实现方式,但是判断逻辑没变;
objectToString
export const objectToString = Object.prototype.toString
直接是Object.prototype.toString
;
toTypeString
export const toTypeString = (value: unknown): string => objectToString.call(value)
对入参执行Object.prototype.toString
;
toRawType
export const toRawType = (value: unknown): string => { // extract "RawType" from strings like "[object RawType]" return toTypeString(value).slice(8, -1) }
和Vue2
的实现方式相同;
isPlainObject
export const isPlainObject = (val: unknown): val is object => toTypeString(val) === '[object Object]'
和Vue2
的实现方式相同;
isIntegerKey
export const isIntegerKey = (key: unknown) => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key
判断一个字符串是不是由一个整数组成的;
isReservedProp
export const isReservedProp = /*#__PURE__*/ makeMap( // the leading comma is intentional so empty string "" is also included ',key,ref,ref_for,ref_key,' + 'onVnodeBeforeMount,onVnodeMounted,' + 'onVnodeBeforeUpdate,onVnodeUpdated,' + 'onVnodeBeforeUnmount,onVnodeUnmounted' )
使用makeMap
生成一个对象,用于判断入参是否是内部保留的属性;
isBuiltInDirective
export const isBuiltInDirective = /*#__PURE__*/ makeMap( 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo' )
使用makeMap
生成一个对象,用于判断入参是否是内置的指令;
cacheStringFunction
const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => { const cache: Record<string, string> = Object.create(null) return ((str: string) => { const hit = cache[str] return hit || (cache[str] = fn(str)) }) as T }
同Vue2
的cached
相同,用于缓存字符串;
camelize
const camelizeRE = /-(\w)/g /** * @private */ export const camelize = cacheStringFunction((str: string): string => { return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')) })
将-
连接的字符串转换为驼峰式,同Vue2
的camelize
相同;
capitalize
const hyphenateRE = /\B([A-Z])/g /** * @private */ export const hyphenate = cacheStringFunction((str: string) => str.replace(hyphenateRE, '-$1').toLowerCase() )
将驼峰式字符串转换为-
连接的字符串,同Vue2
的hyphenate
相同;
capitalize
/** * @private */ export const capitalize = cacheStringFunction( (str: string) => str.charAt(0).toUpperCase() + str.slice(1) )
将字符串首字母大写,同Vue2
的capitalize
相同;
toHandlerKey
/** * @private */ export const toHandlerKey = cacheStringFunction((str: string) => str ? `on${capitalize(str)}` : `` )
将字符串首字母大写并在前面加上on
;
hasChanged
// compare whether a value has changed, accounting for NaN. export const hasChanged = (value: any, oldValue: any): boolean => !Object.is(value, oldValue)
和Vue2
相比,移除了polyfill
,直接使用Object.is
;
invokeArrayFns
export const invokeArrayFns = (fns: Function[], arg?: any) => { for (let i = 0; i < fns.length; i++) { fns[i](arg) } }
批量调用传递过来的函数列表,如果有参数,会将参数传递给每个函数;
def
export const def = (obj: object, key: string | symbol, value: any) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, value }) }
使用Object.defineProperty
定义一个属性,并使这个属性不可枚举;
looseToNumber
/** * "123-foo" will be parsed to 123 * This is used for the .number modifier in v-model */ export const looseToNumber = (val: any): any => { const n = parseFloat(val) return isNaN(n) ? val : n }
将字符串转换为数字,如果转换失败,返回原字符串;
通过注释知道主要用于v-model
的.number
修饰符;
toNumber
/** * Only conerces number-like strings * "123-foo" will be returned as-is */ export const toNumber = (val: any): any => { const n = isString(val) ? Number(val) : NaN return isNaN(n) ? val : n }
将字符串转换为数字,如果转换失败,返回原数据;
getGlobalThis
let _globalThis: any export const getGlobalThis = (): any => { return ( _globalThis || (_globalThis = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}) ) }
获取全局对象,根据环境不同返回的对象也不同;
genPropsAccessExp
const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/ export function genPropsAccessExp(name: string) { return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]` }
生成props
的访问表达式,如果name
是合法的标识符,直接返回__props.name
,否则返回通过JSON.stringify
转换后的__props[name]
;
总结
通过这次的源码阅读,我们巩固了一些基础知识,通过对比Vue2
的工具函数,我们也了解了Vue3
的一些变化;
这些变化个人感觉主要集中在拥抱es6
,可以看到放弃ie
是多么自由而奔放;
话外题,不知道大家有没有发现MDN
上面的浏览器兼容性表格,已经没有了ie
的相关信息。
The above is the detailed content of Let's talk about the 38 tool functions under the Vue3 shared module (source code reading). For more information, please follow other related articles on the PHP Chinese website!

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.