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()
相关推荐
布列瑟农的星空2 小时前
Playwright使用体验
前端·单元测试
卤代烃2 小时前
🦾 可为与不可为:CDP 视角下的 Browser 控制边界
前端·人工智能·浏览器
_XU3 小时前
AI工具如何重塑我的开发日常
前端·人工智能·深度学习
C_心欲无痕3 小时前
vue3 - defineExpose暴露给父组件属性和方法
前端·javascript·vue.js·vue3
鹿人戛3 小时前
HarmonyOS应用开发:相机预览花屏问题解决案例
android·前端·harmonyos
萌萌哒草头将军3 小时前
绿联云 NAS 安装 AudioDock 详细教程
前端·docker·容器
贺今宵4 小时前
安装better-sqlite3报错electron-vite
javascript·sql·sqlite·sqlite3
GIS之路4 小时前
GIS 数据转换:使用 GDAL 将 GeoJSON 转换为 Shp 数据
前端
2501_944446004 小时前
Flutter&OpenHarmony文件夹管理功能实现
android·javascript·flutter
朴shu5 小时前
Luckysheet 远程搜索下拉 控件开发 : 揭秘二开全流程
前端