Vuex 源码解析3 (Plugins)

本文解析了Vuex中的两个核心插件:devtoolPlugin和loggerPlugin。devtoolPlugin用于集成Vue开发者工具,实现状态管理的可视化;loggerPlugin则提供mutation记录功能,便于调试和测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                        Vuex 源码解析3 (Plugins)

一. plugins/devtool.js

     devtoolPlugin 主要功能是利用Vue 的开发者工具和Vuex做配合,通过开发者工具的面板展示Vuex的状态。

 

/* 
  从window对象的__VUE_DEVTOOLS_GLOBAL_HOOK__中获取devtool插件 
 (如果浏览器装了开发者工具)
*/
const devtoolHook =
  typeof window !== 'undefined' &&
  window.__VUE_DEVTOOLS_GLOBAL_HOOK__
export default function devtoolPlugin (store) {
  if (!devtoolHook) return
  /* devtoll插件实例存储在store的_devtoolHook上 */
  store._devtoolHook = devtoolHook
  /* 出发vuex的初始化事件,并将store的引用地址传给deltool插件,使插件获取store的实例 */
  devtoolHook.emit('vuex:init', store)

  /* 
    监听vuex的travel-to-state事件,把当前状态树替换成目标状态树
   (这个功能也是利用Vue开发者工具替换Vuex的状态) 
  */
  devtoolHook.on('vuex:travel-to-state', targetState => {
    /* 重制state */
    store.replaceState(targetState)
  })
  /* 
     订阅store的state变化.
     当store的mutation提交了state的变化,会触发回调函数-----
    (通过devtoolHook派发一个Vuex mutation事件,mutation和rootState作为参数,这样开发者工具就 
      可以观测到Vuex state的实时变化,在面板上展示最新的状态树)
  */
  store.subscribe((mutation, state) => {
    devtoolHook.emit('vuex:mutation', mutation, state)
  })
}

二.  plugins/logger.js

       通常在开发环境中,我们希望实时把mutation的动作及store的state变化实时输出。测试则可以用到该插件。

import { deepCopy } from '../util'
// 默认参数都有默认值
export default function createLogger ({
  collapsed = true,
  filter = (mutation, stateBefore, stateAfter) => true,
  transformer = state => state,
  mutationTransformer = mut => mut
} = {}) {
  // 函数默认返回的是一个函数
  // 执行logger 插件的时候,实际执行的是这个函数
  return store => {
    let prevState = deepCopy(store.state)

    store.subscribe((mutation, state) => {
      if (typeof console === '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
          ? console.groupCollapsed
          : console.group

        // render
        try {
          startMessage.call(console, message)
        } catch (e) {
          console.log(message)
        }

        console.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState))
        console.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation)
        console.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState))

        try {
          console.groupEnd()
        } catch (e) {
          console.log('—— log end ——')
        }
      }
      // 把nextState赋值给prevState ,便于下次mutation
      prevState = nextState
    })
  }
}
function repeat (str, times) {
  return (new Array(times + 1)).join(str)
}
function pad (num, maxLength) {
  return repeat('0', maxLength - num.toString().length) + num
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值