MST

星途 面试题库

面试题:Vuex 中跨组件通信时如何在模块间共享状态

在 Vue 项目中使用 Vuex 进行跨组件通信,假设项目中有多个 Vuex 模块,现在需要在不同模块间共享部分状态,请描述实现思路及关键代码步骤。
21.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 实现思路
    • 可以通过在Vuex的根状态中定义共享状态,然后各个模块通过gettersmutationsactions来访问和修改这些共享状态。
    • 也可以使用Vuex的module嵌套结构,将共享状态相关的模块作为一个独立的子模块,各个需要共享状态的模块通过导入这个子模块来实现共享。
  2. 关键代码步骤(以在根状态定义共享状态为例)
    • 定义Vuex store
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        sharedState: 'default value' // 在根状态定义共享状态
    },
    getters: {
        getSharedState: state => state.sharedState // 定义getter获取共享状态
    },
    mutations: {
        updateSharedState(state, newVal) {
            state.sharedState = newVal; // 定义mutation更新共享状态
        }
    },
    actions: {
        updateSharedStateAction({ commit }, newVal) {
            commit('updateSharedState', newVal); // 定义action调用mutation更新共享状态
        }
    },
    modules: {
        moduleA: {
            // moduleA相关代码,可通过根状态访问共享状态
            getters: {
                getSharedStateInModuleA: (state, getters, rootState) => rootState.sharedState
            },
            actions: {
                updateSharedStateFromModuleA({ rootDispatch }, newVal) {
                    rootDispatch('updateSharedStateAction', newVal);
                }
            }
        },
        moduleB: {
            // moduleB相关代码,可通过根状态访问共享状态
            getters: {
                getSharedStateInModuleB: (state, getters, rootState) => rootState.sharedState
            },
            actions: {
                updateSharedStateFromModuleB({ rootDispatch }, newVal) {
                    rootDispatch('updateSharedStateAction', newVal);
                }
            }
        }
    }
});

export default store;
  • 在组件中使用
<template>
    <div>
        <p>{{ sharedState }}</p>
        <button @click="updateSharedState">Update Shared State</button>
    </div>
</template>

<script>
export default {
    computed: {
        sharedState() {
            return this.$store.getters.getSharedState;
        }
    },
    methods: {
        updateSharedState() {
            this.$store.dispatch('updateSharedStateAction', 'new value');
        }
    }
};
</script>