vue2状态管理(三)-- 插件的使用

vue2状态管理(三)-- 插件的使用

我们修改 state,然后刷新浏览器,状态又变化原来的了,因为 state 是存在内存中的,为了点击刷新,状态不回到原来的,就需要 Vuex 提供的插件功能,当然插件还能实现其他复杂的功能。

如何编写一个 vuex 插件

Vuex 的 store 接受 plugins 选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 作为唯一参数:

const myPlugin = store => {
   
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
   
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
  })
}

使用插件:

const store = new Vuex.Store({
   
  // ...
  plugins: [myPlugin]
})

使用插件本地 state 持久化。

//localstore.js
export default store => {
   
  // 当 store 初始化后调用
  console.log('store 初始化', JSON.stringify(store.state, '', 2))
  // 已经初始化
  // 不能 store.state = '' 直接赋值方式改变 state
  if (localStorage.getItem('state')) store.replaceState(JSON.parse(localStorage.state))
  store.subscribe
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值