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
}