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()
相关推荐
ZC跨境爬虫4 分钟前
跟着 MDN 学CSS day_30:(玩转列表样式,从基础到进阶)
前端·css·html·tensorflow·媒体
ct9789 分钟前
TypeScript 中的泛型
前端·javascript·typescript
IT_陈寒12 分钟前
React hooks闭包陷阱把我坑惨了,原来这才是正确用法
前端·人工智能·后端
nnsix20 分钟前
MVC、MVP、MVVM 架构 笔记
java·开发语言·前端
qq_4203620320 分钟前
前端国际化方案
前端·javascript·vue.js·国际化·reactjs
向上的车轮21 分钟前
React 19 快速入门:拥抱服务端组件与新特性的现代化开发
前端·javascript·react.js
Smile_25422041825 分钟前
vue3 + ts reactive方式清空表单对象
开发语言·前端·javascript
多租户观察室26 分钟前
信通院标准体系2.0深度解读:低代码管理平台进入“精品竞争”时代
前端·低代码·程序员
云水一下29 分钟前
CSS3从零基础到精通(四):终章大项目——纯CSS构建企业品牌展示网站
前端·css3
147API37 分钟前
Claude Opus 4.8 接口与工程落地分析:长任务调用链应该怎么设计
java·前端·数据库