# Vue2.6.x源码阅读 - 3.源码阅读-shared

> 阅读学习`Vue`源码`/src`目录下的`shared`文件夹内的代码

* 根据`src`的目录结构说明，我们自然能够想到通过入口文件进行入手，按其引入的文件以及代码逻辑进行分析。但简单阅读入口文件就能够发现，源码当中充满了各种各样的函数方法，这些方法都来自于`shared`目录中，所以在解读入口文件前，需要对这些方法有一个前置的熟悉。

## 常量 - constants

* 常量文件比较短，所以直接把代码贴上来

  ```javascript
  // @/shared/constants.js
  /* 服务端渲染 */
  export const SSR_ATTR = 'data-server-rendered'

  /* 每个Vue组件都会挂载的成员 */
  export const ASSET_TYPES = [
    'component', // 组件
    'directive', // 指令
    'filter'     // 过滤器
  ]

  /* Vue的12个生命周期钩子函数 */
  export const LIFECYCLE_HOOKS = [
    'beforeCreate',
    'created',
    'beforeMount',
    'mounted',
    // ...
  ]
  ```

## 工具方法 - util

* 类型判断方法，如`isUndef`、`isPromise`等。
* 类型转换方法，如toString、toNumber等。在转换方法中我们可以发现定义了一些与基本数据类型原型方法同名的方法，但都进行了重写，以`toString`为例。

  ```javascript
  /**
   * Convert a value to a string that is actually rendered.
    * 除去Number类型，也对数组与空对象进行了处理
    * 数组与空对象类型使用类型判断方法进行判断
    * _toString为js原生toString方法
    */
  const _toString = Object.prototype.toString
  export function toString (val: any): string {
    return val == null
      ? ''
      : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
        ? JSON.stringify(val, null, 2)
        : String(val)
  }
  ```
* 其他重要方法
  1. **makeMap**: 用于生成一个带有缓存的函数，用于判断数据是否为缓存中的数据。

     ```javascript
     /**
     * Make a map and return a function for checking if a key is in that map.
      */
     export function makeMap (
      str: string,
      expectsLowerCase?: boolean
     ): (key: string) => true | void {
      const map = 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方法使用例子，两个类型判断的方法
     * isBuiltInTag 用于判断当前标签是否为Vue内置标签
     * isReservedAttribute 用于标签当前属性是否为Vue内置属性
     */
     export const isBuiltInTag = makeMap('slot,component', true)

     export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is')
     ```
  2. **remove**: 删除一个数组元素
  3. **cached**: 生成一个带有缓存的函数(闭包)

     ```javascript
     export function cached<F: Function> (fn: F): F {
      const cache = Object.create(null)
      return (function cachedFn (str: string) {
        // 判断传入的数据是否已缓存，如果已缓存，hit就有数据，反之为undefined
        const hit = cache[str]
        // 这里的return非常精简优雅，当hit为undefined时，同时进行了赋值与返回的操作
        return hit || (cache[str] = fn(str))
      }: any)
     }
     ```
  4. 字符串格式化转换方法**camelize**(下划线字符串驼峰化)、**capitalize**(字符串大写)、hyphenate(驼峰字符串下划线化)。字符串转换方法都使用了上述`cached`方法作为性能优化的技巧。

     ```javascript
     // 使用cached方法的camelize
     const camelizeRE = /-(\w)/g
     export const camelize = cached((str: string): string => {
      return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
     })
     ```
  5. **looseEqual**: 比较两个对象是否相等。在js中无法通过`==`对两个进行比较，而通过内存地址进行比较。从实际使用意义来考虑，我们通常会将两个各个属性值均相等的对象称为相等对象，如最简单的`{}`与`{}`相等。`looseEqual`方法就完成了这个比较功能。由于代码较长，所以这里只对它的实现思路进行描述。
     * 获取入参对象a与b，方法入参类型均为`any`。
     * 对比a与b的长度，长度相同的情况下，遍历a中的成员，判断每一个成员是否都在b中，且与b中对应成员的值相等。这里用的遍历方法会对a的类型进行判断，不同类型通过不同方法进行遍历，如`object`使用`Object.keys()`。
     * 再对b中对成员进行相同对一遍操作，与a进行比较。排除a是b子集的情况。
     * a与b中的成员存在引用类型，需要进行递归。
     * 该思路的实现思路其实比较简单，类似比较两个集合是否相同。关注点其实更应该落在其对于类型的处理上，先用`typeof`来对引用类型与非引用类型进行区分。非引用类型对处理会比较简单，可以通过`===`进行比较，也可以通过转`String`类型进行比较。而引用类型的处理，具体会对Object、Array、Date三个类型进行区别处理。
     * 由于该方法主要服务于Vue的数据比较，不存在比较正则表达式的情况，所以方法没有对正则表达式类型进行比较处理。如果需要考虑其他类型，可以在源码中添加`else-if`逻辑。
  6. **once**: 让一个事件(函数)只调用一次。Vue中的`v-once`指令就是应用了这个方法的思想。

     ```javascript
     /**
     * Ensure a function is called only once.
      */
     export function once (fn: Function): Function {
      let called = false
      return function () {
        // 通过闭包判断该方法是否已经被调用
        if (!called) {
          called = true
          fn.apply(this, arguments)
        }
      }
     }
     ```

## 小结

* 从`shared`中可以学习到一些标准化工程的构建思路，提前定义好工程中所需要的常量与工具类方法，一来能够有效的精简工程中的通用代码处理逻辑，二来也能够后续的代码维护。同时通过源码阅读，也能够看到一个好的工程离不开优美规范的代码。以及在代码编写过程中无时不想着的性能优化。三者也能学习到能够在面试中可能会考到的工具类方法的算法逻辑。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaobaiha.gitbook.io/tech-share/vue/vue2.6.x-yuan-ma-yue-du/3.-yuan-ma-yue-du-shared.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
