一些觉得有用的trick

307 阅读2分钟

整理了一些觉得有用的小技巧

将Vue变量保存(导出供其他文件使用),同时可以判断是否重复注册插件

export const Vue
export function install (_Vue) {
  if (Vue && _Vue === Vue) {
    if (__DEV__) {
      console.error(
        '[vuex] already installed. Vue.use(Vuex) should be called only once.'
      )
    }
    return
  }
  Vue = _Vue
  applyMixin(Vue)
}

reduce()函数的使用场景

之前是了解reduce()的用法,但是往往理论和实践是脱节的,在阅读Vuex源码的过程中,发现了reduce()的妙用(才疏学浅)

// 以下是截取vuex源码中的一小部分
// vuex为了保证全局状态的可复用性,创建了module树状结构的模块集合和命名空间概念
/**
    params:path (Array) path数组保存当前模块从父到子的路径key
    return module (Object) 函数按照path路径依次查找到最后一级的module模块
**/
get (path) {
    return path.reduce((module, key) => {
      return module.getChild(key)
    }, this.root)
}
/**
    params: path (Array) path数组保存当前模块从父到子的路径key
    return namespaceKey (String) 函数按照path路径依次拼接命令空间的key
**/
getNamespace (path) {
    let module = this.root
    return path.reduce((namespace, key) => {
      module = module.getChild(key)
      return namespace + (module.namespaced ? key + '/' : '')
    }, '')
}

异步函数队列执行

路由切换的时候会执行一系列导航钩子,在vue-router官网上有详细的执行顺序,runQueue()用于维护导航钩子的执行

/**
    params: queue (Array) 导航钩子集合,每个导航钩子类似传入to,from,next的函数
    params: fn (Function) 执行每个导航钩子函数
    params: cb (Function) 传入的导航钩子执行完成后,complete回调
    
    这个方法让我们执行异步函数看起来就像同步执行,只有当前一个navigationGuard执行完成,调用next(),才会执行下一个navigationGuard,我们完全可以决定调用next()的时机
**/
export function runQueue (queue: Array<?NavigationGuard>, fn: Function, cb: Function) {
  const step = index => { 
    if (index >= queue.length) {
      cb()
    } else {
      if (queue[index]) {
        fn(queue[index], () => {
          step(index + 1)
        })
      } else {
        step(index + 1)
      }
    }
  }
  step(0)
}

利用闭包,将fn保留返回一个提供删除操作的api回调

闭包不只是一个停留在面试环节的考察概念,而应该是出现在代码中的好工具

function registerHook (list: Array<any>, fn: Function): Function {
  list.push(fn)
  return () => {
    const i = list.indexOf(fn)
    if (i > -1) list.splice(i, 1)
  }
}

低代码,封装工具函数-遍历一个对象

export function forEachValue (obj, fn) {
  Object.keys(obj).forEach(key => fn(obj[key], key))
}
forEachMutation (fn) {
    if (this._rawModule.mutations) {
      forEachValue(this._rawModule.mutations, fn)
    }
}
module.forEachMutation((mutation, key) => {
    const namespacedType = namespace + key
    registerMutation(store, namespacedType, mutation, local)
})

以上也是一些在阅读源码的过程中整理的小技巧,方便以后阅读~~

日日自新