资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

vuex中插件如何编写-创新互联

这篇文章将为大家详细讲解有关vuex 中插件如何编写,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

成都创新互联公司主营金牛网站建设的网络公司,主营网站建设方案,成都APP应用开发,金牛h5微信小程序开发搭建,金牛网站营销推广欢迎金牛等地区企业咨询

一、官方文档

1、第一步

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

2、第二步

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

二、编写一个打印日志的插件

1、函数的书写

import _ from 'lodash';
function logger() {
 return function(store) {
 let prevState = store.state;
 store.subscribe((mutations, state) => {
  console.log('prevState', prevState);
  console.log(mutations);
  console.log('currentState', state);
  prevState = _.cloneDeep(state);
 });
 };
}

2、使用

export default new Vuex.Store({
 modules: {
 ...
 },
 strict: true,
 plugins: process.NODE_ENV === 'production' ? [] : [logger()]
});

三、 vuex 数据持久化

1、函数的书写

function vuexLocal() {
 return function(store) {
 const local = JSON.parse(localStorage.getItem('myvuex')) || store.state;
 store.replaceState(local);
 store.subscribe((mutations, state) => {
  const newLocal = _.cloneDeep(state);
  sessionStorage.setItem('myvuex', JSON.stringify(newLocal));
 });
 };
}

2、使用

export default new Vuex.Store({
 modules: {
 ...
 },
 strict: true,
 plugins: process.NODE_ENV === 'production' ? [vuexLocal()] : [logger(), vuexLocal()]
});

3、类似的第三方库

1. vuex-persistedstate

2. vuex-persist

关于“vuex 中插件如何编写”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


网页题目:vuex中插件如何编写-创新互联
网页URL:http://cdkjz.cn/article/phsse.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220