1、插件
插件实际是一个函数
Vuex 的 store 接受
plugins
选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 作为唯一参数:定义 插件
export const saveInLocal = store => { // 当 store 初始化后调用 console.log('store初始化了') store.subscribe((mutaion, state) => { // 每次 mutatios 之后调用 // mutation 的格式为 { type, payload } console.log('提交mutation') }) }
使用插件
import { saveInLocal } from './plugin/saveInLocal' export default new Vuex.Store({ state, mutations, actions, getters, modules: { user }, plugins: [ saveInLocal ] })
一个小案例(缓存本地 State)
export const saveInLocal = store => { // 当 store 初始化后调用 // 2、刷新时,如果本地有数据,则将JSON变为store,替换store if(localStorage.state) store.replaceState(JSON.parse(localStorage.state)) store.subscribe((mutaion, state) => { // 每次 mutatios 之后调用 // 1、调用时,将state变为 JSON 存储到 localStorage localStorage.state = JSON.stringify(state) }) }
2、严格模式
- 好处:在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到
- 一般在开发环境下使用严格模式
- 不要在发布环境下启用严格模式!避免性能损耗
如何开启严格模式
// 仅需在创建 store 的时候传入 strict: true: const store = new Vuex.Store({ // ... // 判断是否是开发模式 strict: process.env.NODE_ENV === 'development' })
3、表单处理 (v-model)
如果开启了严格模式,便无法在 Vuex 的 state 上使用 v-model
1、解决方法一:给
input
中绑定 value,然后侦听input
或者change
事件,在事件回调中调用一个方法<a-input :value="stateValue" @input="handleStateValueChange" />
computed: { ...mapState({ stateValue: state => state.stateValue }), }, methods: { handleStateValueChange( val ) { this.$store.commit({ type: 'SET_STATE_VALUE', stateValue: val }) } }
2、解决方法二:使用带有 setter 的双向绑定计算属性
<a-input v-model="stateValue" />
computed: { stateValue: { get () { return this.$store.state.stateValue }, set(value) { this.$store.commit({ type: 'SET_STATE_VALUE', stateValue: value }) } }, }