Vuex 除了提供的存取能力,还提供了一种插件能力,可以监控 store 的变化过程来做一些事情
Vuex 的 store 接受 plugins 选项,在实例化 Store 的时候可以传入插件,它是一个数组,然后在执行 Store 构造函数的时候,会执行这些插件
const {
plugins = [],
strict = false
} = options
// apply plugins
plugins.forEach(plugin => plugin(this))
在实际项目中,用到的最多的就是 Vuex 内置的 Logger 插件,它能够帮助追踪 state 变化,然后输出一些格式化日志
下面就来分析这个插件的实现
Logger 插件
Logger 插件的定义在 src/plugins/logger.js 中
export default function createLogger ({
collapsed = true,
filter = (mutation, stateBefore, stateAfter) => true,
transformer = state => state,
mutationTransformer = mut => mut,
actionFilter = (action, state) => true,
actionTransformer = act => act,
logMutations = true,
logActions = true,
logger = console
} = {}) {
return store => {
let prevState = deepCopy(store.state)
if (typeof logger === 'undefined') {
return
}
if (logMutations) {
store.subscribe((mutation, state) => {
const nextState = deepCopy(state)
if (filter(mutation, prevState, nextState)) {
const formattedTime = getFormattedTime()
const formattedMutation = mutationTransformer(mutation)
const message = `mutation ${mutation.type}${formattedTime}`
startMessage(logger, message, collapsed)
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))
endMessage(logger)
}
prevState = nextState
})
}
if (logActions) {
store.subscribeAction((action, state) => {
if (actionFilter(action, state)) {
const formattedTime = getFormattedTime()
const formattedAction = actionTransformer(action)
const message = `action ${action.type}${formattedTime}`
startMessage(logger, message, collapsed)
logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction)
endMessage(logger)
}
})
}
}
}
function repeat (str, times) {
return (new Array(times + 1)).join(str)
}
function pad (num, maxLength) {
return repeat('0', maxLength - num.toString().length) + num
}
插件函数接收的参数是 store 实例,它执行了 store.subscribe 方法,先来看一下 subscribe 的定义
// 往this._subscribers去添加一个函数,并返回一个unsubscribe的方法
subscribe (fn, options) {
return genericSubscribe(fn, this._subscribers, options)
}
function genericSubscribe (fn, subs, options) {
if (subs.indexOf(fn) < 0) {
options && options.prepend
? subs.unshift(fn)
: subs.push(fn)
}
return () => {
const i = subs.indexOf(fn)
if (i > -1) {
subs.splice(i, 1)
}
}
}
而在执行 store.commit 的方法的时候,会遍历 this._subscribers 执行它们对应的回调函数
commit (_type, _payload, _options) {
// check object-style commit
const {
type,
payload,
options
} = unifyObjectStyle(_type, _payload, _options)
const mutation = { type, payload }
const entry = this._mutations[type]
if (!entry) {
if (__DEV__) {
console.error(`[vuex] unknown mutation type: ${type}`)
}
return
}
this._withCommit(() => {
entry.forEach(function commitIterator (handler) {
handler(payload)
})
})
this._subscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.forEach(sub => sub(mutation, this.state))
if (
__DEV__ &&
options && options.silent
) {
console.warn(
`[vuex] mutation type: ${type}. Silent option has been removed. ` +
'Use the filter functionality in the vue-devtools'
)
}
}
回到 Logger 函数,它相当于订阅了 mutation 的提交,它的 prevState 表示之前的 state,nextState 表示提交 mutation 后的 state,这两个 state 都需要执行 deepCopy 方法拷贝一份对象的副本,这样对他们的修改就不会影响原始 store.state
接下来就构造一些格式化的消息,打印出一些时间消息 message, 之前的状态 prevState,对应的 mutation 操作 formattedMutation 以及下一个状态 nextState
最后更新 prevState = nextState,为下一次提交 mutation 输出日志做准备
Vuex 从设计上支持了插件,很好地从外部追踪 store 内部的变化,Logger 插件在开发阶段也提供了很好地指引作用
当然也可以自己去实现 Vuex 的插件,来帮助实现一些特定的需求