首页 > 解决方案 > 使用 vue3 和 webpack 模块联合进行状态管理

问题描述

我正在使用带有 Vuejs3 和 webpack 5 模块联合的 MFE 创建一个应用程序。使用 Vue 制作的一个主要应用程序将使用其他应用程序(应该与框架无关),我需要将状态从我的 Vue shell 共享到其他应用程序。

我尝试使用 Composition api 创建一个商店,但该值仅在调用该事件的应用程序中更新。

这是我从 vue shell 中公开的商店:

import { reactive, toRefs } from 'vue'

const state = reactive({
  data: {
    quantity: 1,
  },
})

export default function useStoreData() {
  const updateQuantity = (quantity) => {
    state.data.quantity += quantity
  }

  return {
    ...toRefs(state),
    updateQuantity,
  }
}

在 Vue 外壳中:

<template>
    <div>
      <button @click="updateQuantity(1)">FOO +1</button>
      <div>Quantity = {{ data.quantity }} </div>
    </div>
</template>

<script setup>
import useStoreData from '../store/storeData'
const { updateQuantity, data } = useStoreData()
</script>

当我单击“FOO +1”按钮时,值会更新 +1。

在我的远程应用程序中:

<template>
  <div>
    <button @click="updateQuantity(5)">BAR +5</button>
    <div>Quantity = {{ data.quantity }}</div>
  </div>
</template>

<script setup>
import store from 'store/storeData'

const useStoreData = store
const { data, updateQuantity } = useStoreData()
</script>

当我单击按钮“BAR +5”时,值会更新 +5

但是每次我单击其中一个按钮时,另一个应用程序中的值都不会更新。

我错过了什么 ?

标签: vue.jswebpackvuejs3state-managementwebpack-module-federation

解决方案


Needed to add the shell app as a remote of itself then import the store in the shell app, same way as i'm doing in my remote app.

Here is the vue.config.js of the shell, where I need to expose AND remote the store.

const { ModuleFederationPlugin } = require('webpack').container
const deps = require('./package.json').dependencies

module.exports = {
  publicPath: '/',
  configureWebpack: {
    plugins: [
      new ModuleFederationPlugin({
        name: 'shell',
        filename: 'remoteEntry.js',
        remotes: {
          test: 'test@http://localhost:8081/remoteEntry.js',
          test2: 'test2@http://localhost:8082/remoteEntry.js',
          store: 'shell@http://localhost:8080/remoteEntry.js', <= ADDED HERE the remote of itself
        },
        exposes: {
          './storeData': './src/store/storeData.js',
        },
        shared: [
          {
            ...deps,
          },
        ],
      }),
    ],
  },
  devServer: {
    port: 8080,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
    },
  },
}

In the Vue shell app:

<script setup>
// import useStoreData from '../store/storeData' <= wrong
import store from 'store/storeData' <= good
</script>

推荐阅读