美文网首页
VUEX源码解析

VUEX源码解析

作者: Hsugar | 来源:发表于2020-03-08 17:23 被阅读0次

    /plugins/devtool.js

    • 浏览器开发者工具支持监控VueX
    const devtoolHook =
      typeof window !== 'undefined' &&
      window.__VUE_DEVTOOLS_GLOBAL_HOOK__
    
    export default function devtoolPlugin (store) {
      if (!devtoolHook) return
    
      store._devtoolHook = devtoolHook
    
      devtoolHook.emit('vuex:init', store)
    
      devtoolHook.on('vuex:travel-to-state', targetState => {
        store.replaceState(targetState)
      })
    
      store.subscribe((mutation, state) => {
        devtoolHook.emit('vuex:mutation', mutation, state)
      })
    }
    

    /plugins/logger.js

    • repeat
    function repeat (str, times) {
      return (new Array(times + 1)).join(str)
    }
    

    解析:字符串重复几次repeat('0', 5)会返回'00000'

    • pad
    function pad (num, maxLength) {
      return repeat('0', maxLength - num.toString().length) + num;
    }
    

    解析:给数字补零,如pad(5, 5) 会返回'000005'

    • createLogger
      prev sate 代表之前的数据,mutations代表经过vuex中的mutations中方法修改后的数据,可以通过这个logger插件可以明细的看到数据的变化
    import _ from 'lodash';
    export function deepCopy (obj, cache = []) {
      // just return if obj is immutable value
      if (obj === null || typeof obj !== 'object') {
        return obj;
      }
    
      // if obj is hit, it is in circular structure
      const hit = _.find(cache, c => c.original === obj);
      if (hit) {
        return hit.copy;
      }
    
      const copy = Array.isArray(obj) ? [] : {};
      // put the copy into cache at first
      // because we want to refer it in recursive deepCopy
      cache.push({
        original: obj,
        copy
      });
    
      Object.keys(obj).forEach(key => {
        copy[key] = deepCopy(obj[key], cache);
      });
    
      return copy;
    }
    
    export default function createLogger ({
      collapsed = true,    // 自动展开记录的 mutation
      filter = (mutation, stateBefore, stateAfter) => true,
      transformer = state => state,  // 在开始记录之前转换状态
      mutationTransformer = mut => mut,  // mutation 按照 { type, payload } 格式记录
      logger = console    // 自定义 console 实现,默认为 `console`
    } = {}) {
      return store => {
        let prevState = deepCopy(store.state)
    
        store.subscribe((mutation, state) => {
          if (typeof logger === 'undefined') {
            return
          }
          const nextState = deepCopy(state)
    
          if (filter(mutation, prevState, nextState)) {
            const time = new Date()
            const formattedTime = ` @ ${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}`
            const formattedMutation = mutationTransformer(mutation)
            const message = `mutation ${mutation.type}${formattedTime}`
            const startMessage = collapsed
              ? logger.groupCollapsed
              : logger.group
    
            // render
            try {
              startMessage.call(logger, message)
            } catch (e) {
              console.log(message)
            }
    
            logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState))
            logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation)
            logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState))
    
            try {
              logger.groupEnd()
            } catch (e) {
              logger.log('—— log end ——')
            }
          }
    
          prevState = nextState
        })
      }
    }
    

    相关文章

      网友评论

          本文标题:VUEX源码解析

          本文链接:https://www.haomeiwen.com/subject/lhoxrhtx.html