vue.js - 使用 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
但是每次我单击其中一个按钮时,另一个应用程序中的值都不会更新。
我错过了什么 ?
解决方案
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>
推荐阅读
- javascript - 在 d3 数据映射中包含键
- javascript - 没有库的 JavaScript 自定义确认函数
- sql - Power BI - DAX List.Select 语法以返回特定记录
- javascript - 使用 JavaScript 将字符串类型的数组转换为常规数组
- attributeerror - pydicom AttributeError:数据集没有属性“ImagePositionPatient”
- javascript - 如何在测验中显示单答案问题的先前答案
- aws-lambda - 使用无服务器框架,是否可以让函数在本地相互调用?类似于 SAM 的 sam local start-lambda?
- excel - 无法完全保护 Excel 工作表
- php - 如何对来自对象响应的结果进行 json 编码?
- vue.js - 如何在多用户 Vue 应用程序中处理刷新