uniApp 封装VUEX

Vuex Store (index.js)

js 复制代码
import Vue from 'vue';
import Vuex from 'vuex';
import Cookies from 'js-cookie';

Vue.use(Vuex);

const saveStateKeys = ['vuex_user', 'vuex_token', 'vuex_demo'];

const initialState = {
    vuex_user: { name: '用户信息' },
    vuex_token: Cookies.get('token') || '',
    vuex_isdev: false,
    vuex_version: '1.0.1',
    vuex_demo: '绛紫',
    vuex_testStore: '测试vuexStore',
};

const store = new Vuex.Store({
    state: {
        ...initialState,
    },
    mutations: {},
    actions: {
        dynamicAction(context, payload) {
            return new Promise((resolve, reject) => {
                context.commit(payload.type, payload.value)
                    .then(resolve)
                    .catch(reject);
            });
        },
    },
});

// 动态生成 mutations 和 actions
const createMutation = (key) => (state, value) => {
    state[key] = value;
    saveLifeData(key, value);
    if (key === 'vuex_token') {
        Cookies.set('token', value);
    }
};

const createAction = (key) => ({ commit }, value) =>
    new Promise((resolve, reject) => {
        commit(`SET_${key.toUpperCase()}`, value)
            .then(resolve)
            .catch(reject);
    });

saveStateKeys.forEach(key => {
    store.commit(`ADD_MUTATION_${key.toUpperCase()}`, createMutation(key));
    store.commit(`ADD_ACTION_${key.toUpperCase()}`, createAction(key));
});

function saveLifeData(key, value) {
    if (saveStateKeys.includes(key)) {
        let tmp = uni.getStorageSync('lifeData') || {};
        tmp[key] = value;
        uni.setStorageSync('lifeData', tmp);
    }
}

export default store;

Mixin ($u.mixin.js)

js 复制代码
import { mapState, mapActions } from 'vuex';
import store from '@/store';

const $uStoreKey = Object.keys(store.state);

const dynamicMapActions = (actionsObj) => {
    return Object.fromEntries(
        Object.entries(actionsObj).map(([actionName, action]) => [
            actionName,
            action.bind(null, store.dispatch),
        ])
    );
};

module.exports = {
    beforeCreate() {
        this.$u = {
            vuex: (name, value) => {
                if (value !== undefined) {
                    this[`update${name.charAt(0).toUpperCase() + name.slice(1)}`](value);
                } else {
                    return this[name];
                }
            },
        };
    },
    computed: {
        ...mapState($uStoreKey.filter(key => key.startsWith('vuex_'))),
    },
    methods: {
        ...dynamicMapActions({
            ...store._modulesNamespaceMap['dynamic'].namespacedActions,
        }),
    },
};

使用示例

html 复制代码
<template>
  <div>
    <h1>欢迎,{{ user.name }}!</h1>
    <button @click="changeName">更改名字</button>
  </div>
</template>

<script>
import uMixin from '@/mixins/u.mixin.js';

export default {
  mixins: [uMixin],
  onShow() {
     this.$u.vuex('vuex_user', { name: '新用户' });
	 console.log('初始用户信息:', this.$u.vuex('vuex_user'));
  },
  methods: {
    changeName() {
      this.$u.vuex('vuex_user', { name: '新用户' });
    },
  },
};
</script>

全局混入

js 复制代码
import Vue from 'vue'
import store from '@/store';
// 引入uView提供的对vuex的简写法文件
let vuexStore = require('@/store/$u.mixin.js');
Vue.mixin(vuexStore);
const app = new Vue({
	store
})
app.$mount()
相关推荐
2501_915918411 天前
iOS 开发全流程实战 基于 uni-app 的 iOS 应用开发、打包、测试与上架流程详解
android·ios·小程序·https·uni-app·iphone·webview
IT_陈寒1 天前
Java性能优化:10个让你的Spring Boot应用提速300%的隐藏技巧
前端·人工智能·后端
whysqwhw1 天前
Hippy 跨平台框架扩展原生自定义组件的完整实现方案对比
前端
黑马源码库miui520861 天前
JAVA同城打车小程序APP打车顺风车滴滴车跑腿源码微信小程序打车源码
java·微信·微信小程序·小程序·uni-app
dasseinzumtode1 天前
nestJS 使用ExcelJS 实现数据的excel导出功能
前端·后端·node.js
子兮曰1 天前
🔥C盘告急!WSL磁盘暴增?三招秒清20GB+空间
前端·windows·docker
Jinuss1 天前
Vue3源码reactivity响应式篇之EffectScope
前端·vue3
stoneship1 天前
网页截图API-Npm工具包分享
前端
Jedi Hongbin1 天前
Three.js shader内置矩阵注入
前端·javascript·three.js
etcix1 天前
dmenux.c: integrate dmenu project as one file
c语言·前端·算法