美文网首页
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
    })
  }
}

相关文章

  • 关于一些Vue的文章。(1)

    原文链接我的blog,欢迎STAR。 今天分享的一篇文章是关于vuex的源码解析的,链接vuex源码解析,在现在所...

  • Vuex源码解析

    写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue...

  • VUEX源码解析

    /plugins/devtool.js 浏览器开发者工具支持监控VueX /plugins/logger.js r...

  • Vuex源码解析

    手写vuex核心代码 vuex基本用法 分析 我们是通过new Vuex.store(option)获得一个sto...

  • Vuex 2.0 学习笔记(二):源码阅读

    上一章总结了 Vuex 的框架原理,这一章我们将从 Vuex 的入口文件开始,分步骤阅读和解析源码。由于 Vuex...

  • vuex源码解析(2.3.1)

    在网上有找到一些关于vuex源码分析的文章,有的写的很不错,挺详细的。但是在阅读的过程中还是发现很多地方不理解,所...

  • Vuex源码分析

    Vuex 源码学习 注释 源码目录 Vuex 核心 API: 插件安装 引入了 src/index.js 暴露的对...

  • ios三方库解析

    YYCache 源码解析 YTKNetwork 源码解析 MJRefresh 源码解析 VVeboTableVie...

  • iOS 一些框架源码解析

    YYCache 源码解析 YTKNetwork源码解析 MJRefresh 源码解析 VVeboTableView...

  • EventBus源码解析(三):Post/PostSticky

    EventBus源码解析(一):概述EventBus源码解析(二):RegisterEventBus源码解析(三)...

网友评论

      本文标题:VUEX源码解析

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