uniApp 封装VUEX

ops/2024/10/20 5:41:37/

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

http://www.ppmy.cn/ops/56286.html

相关文章

【linux/shell】shell中实现函数重载

在 shell 脚本中&#xff0c;函数重载&#xff08;Function Overloading&#xff09;的概念与一些编程语言&#xff08;如 Java 或 C#&#xff09;中的函数重载不同。在这些编程语言中&#xff0c;你可以定义多个同名函数&#xff0c;只要它们的参数列表不同。然而&#xff0c;…

求函数最小值-torch版

目标&#xff1a;torch实现下面链接中的梯度下降法 先计算 的导函数 &#xff0c;然后计算导函数 在处的梯度 (导数) 让 沿着 梯度的负方向移动&#xff0c; 自变量 的更新过程如下 torch代码实现如下 import torchx torch.tensor([7.5],requires_gradTrue) # print(x.gr…

Windows10系统下mysql5.6的安装步骤

1.下载mysql 下载地址&#xff1a;https://downloads.mysql.com/archives/community/ 在这里我们下载zip的包 2.解压mysql包到指定目录 3. 添加my.ini文件 # For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.6/en/server-configurat…

代码技巧专题 -- 使用策略模式编写HandleService

一.前言 最近项目有实习的同事加入&#xff0c;很多实习同事反映&#xff0c;看不懂项目中的一些使用了设计模式的代码&#xff0c;比如HandleService&#xff0c;Chains&#xff0c;Listener等。本篇就介绍一下策略模式在项目中的使用&#xff0c;也就是我们常在项目中看到的X…

向新求质 智赋广西,2024华为数智转型助力企业高质量发展论坛在南宁举办

7月5日以“向新求质 智赋广西”为主题的2024华为数智转型助力企业高质量发展论坛在南宁成功举办。来自广西区管企业、驻桂央企和国有企业等80余位中高层管理者&#xff0c;与华为业务变革专家、数字化转型专家共同探讨企业数字化转型新路径&#xff0c;为企业创新转型发展献计献…

VPN 的入门介绍

VPN&#xff08;虚拟专用网络&#xff09; 简介 虚拟专用网络&#xff0c;简称虚拟专网&#xff08;VPN&#xff09;&#xff0c;其主要功能是在公用网络上建立专用网络&#xff0c;进行加密通讯。在企业网络中有广泛应用。VPN网关通过对数据包的加密和数据包目标地址的转换实…

c++入门基础篇(上)

目录 前言&#xff1a; 1.c&#xff0b;&#xff0b;的第一个程序 2.命名空间 2.1 namespace的定义 2.2 命名空间使用 3.c&#xff0b;&#xff0b;输入&输出 4.缺省参数 5.函数重载 前言&#xff1a; 我们在之前学完了c语言的大部分语法知识&#xff0c;是不是意…

数据结构第10节:平衡树

平衡树是一种特殊的二叉搜索树&#xff0c;它的设计目的是为了保持树的平衡&#xff0c;从而保证所有操作的时间复杂度保持在O(log n)&#xff0c;即使在最坏的情况下也是如此。最常见的平衡树之一是AVL树&#xff0c;它是以发明者G.M. Adelson-Velsky和E.M. Landis的名字命名的…