vue3封装vuex状态管理器
1、在store下新建modeules文件夹,默认的store/index.js引入使用
import { createStore } from 'vuex'
// 获得全部module
const files = require.context('./modeules', false, /\.js$/)
const modules = {}
// 收集
files.keys().forEach((key) => {
// 文件名为key
modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})
Object.keys(modules).forEach((key) => {
// 带命名空间,防止不唯一
modules[key]['namespaced'] = true
})
const store = createStore({ modules })
/**
* 安装vuex
* @param {*} app
*/
export function installStore(app) {
app.use(store)
}
export default store
2、对应新建vuex共享文件
/**
* @description demo
*/
// 状态树
const state = () => ({
info: '默认demo',
})
// 获取
const getters = {
getInfo: (state) => state.info,
}
// 修改
const mutations = {
changeInfo(state, updateInfo) {
state.info = updateInfo
},
}
// 异步修改
const actions = {}
export default {
state,
getters,
mutations,
actions,
}
3、页面使用
<template>
<div>
<h1>产品概述</h1>
{{ $store.getters["demo/getInfo"] }}
<el-button @click="testVuex">测试demo</el-button>
{{ $store.getters["actions/getInfo"] }}
<el-button @click="testactionVuex">测试actions</el-button>
</div>
</template>
<script>
import { useStore } from "vuex";
import { reactive, ref, onMounted, toRefs } from "vue";
export default {
setup(props, { emit }) {
const store = useStore();
const returnIfo = ref("");
const data = reactive({});
const method = reactive({
testVuex() {
store.commit("demo/changeInfo", "测试vuexdemo成功");
},
testactionVuex() {
store.commit("actions/changeInfo", "测试vuexactions成功");
},
});
onMounted(() => {});
return { ...toRefs(data), ...method };
},
};
</script>
<style>
</style>
4、实现效果