uniApp 封装VUEX

Vuex Store (index.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)

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,
        }),
    },
};

使用示例

<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>

全局混入

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()


相关推荐

  1. uniApp 封装VUEX

    2024-07-09 20:10:04       20 阅读
  2. HBuilderX uniapp+vue3+vite axios封装

    2024-07-09 20:10:04       25 阅读
  3. vueuniapp中使用 websocket并封装js

    2024-07-09 20:10:04       26 阅读
  4. uniapp 接口请求封装

    2024-07-09 20:10:04       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 20:10:04       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 20:10:04       56 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 20:10:04       46 阅读
  4. Python语言-面向对象

    2024-07-09 20:10:04       57 阅读

热门阅读

  1. H5与小程序:两者有何不同?

    2024-07-09 20:10:04       21 阅读
  2. 论文引用h指数

    2024-07-09 20:10:04       29 阅读
  3. 强化学习(Reinforcement Learning,简称RL)

    2024-07-09 20:10:04       29 阅读
  4. npm证书过期问题

    2024-07-09 20:10:04       20 阅读
  5. GitHub使用教程(小白版)

    2024-07-09 20:10:04       16 阅读
  6. WebXR:Web上的虚拟与增强现实技术

    2024-07-09 20:10:04       28 阅读