uni-app如何將vuex模塊化

如何在uni-app使用vuex
http://www.itdecent.cn/p/c288b8e6067c

目錄結構為

|---demo1.js
|---demo2.js
index.js

index.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const context = require.context('./modules', false, /\.js$/);
const moduleStores = {};

context.keys().forEach(key => {
    // 獲取讀取到的文件名字并且截取
    const fileName = key.slice(2, -3);
    //通過 context(key)導出文件內容
    const fileModule = context(key).default;
    moduleStores[fileName] = {
        ...fileModule,
    };
});
export default new Vuex.Store({
    modules: {
        ...moduleStores,
    },
});

demo1.js

const demoname = {
    fn: 'fn',
}
const store = {
    state: {
        demo: '名字'
    },
    getters: {
        getLocale: state => {
            return state.demo + 321
        }
    },
    mutations: {
        [demoname.fn]: (state, localeVal) => {
            console.log('被執(zhí)行了', localeVal)
        }
    },
    actions: {
        demoactions: ({ commit }, localeVal) => {
            commit(demoname.fn, localeVal)
        }
    }
}
export default store

demo2.js同上

頁面使用

<template>
    <view class="content">
        <view class="text-area">
            <view class="title">{{demo1.demo}}</view>
            <view class="title">{{getLocale}}</view>
        </view>
    </view>
</template>

<script>
    import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
    export default {
        data() {
            return {
                title: 'Hello'
            }
        },
        computed: {
            ...mapGetters(['getLocale']),
            ...mapState([
                'demo1'
            ])
        },
        onLoad() {
            this.fn('傳遞的內容')
            this.demoactions('這是一個異步')
        },
        methods: {
            ...mapMutations([
                'fn'
            ]),
            ...mapActions([
                'demoactions'
            ])
        }
    }
</script>

<style>
</style>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容