微前端下element-ui弹框偏移问题解决
作者:segmentfault
本章主要是解决无界微前端环境下element-ui弹框偏移问题,如果你用的是其他微前端框架,且提供了jsloader这种预处理器,则可以举一反三解决同样的问题
安装依赖
首先,我使用的是无界官方源码,下载地址:无界微前端源码如图已经下载到本地了:使用pnpm i安装一下依赖

如果报错,请更新你的nvm或者使用16.19.0版本的node
启动官网例子
npm run start,正确启动的话可以看到一下页面:

点击进入vue2的dialog页面
我们打开examples\vue2\src\main.js,在顶部任意地方加入:
import Row from "element-ui/lib/row"; import Col from "element-ui/lib/col"; import "element-ui/lib/theme-chalk/row.css"; import "element-ui/lib/theme-chalk/col.css"; [Row, Col].forEach((element) => Vue.use(element));
如图:

打开examples\vue2\src\views\Dialog.vue,写入代码:
<template>
<a-button @click="fullDialogVisible = true" style="margin-left: 20px">点击打开全屏弹窗</a-button>
<el-dialog title="全屏弹窗" fullscreen :visible.sync="fullDialogVisible" width="30%">
<el-row type="flex" justify="space-between">
<el-col :span="6"
><div class="grid-left">
<el-select v-model="value" placeholder="el-select">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
</el-select></div
></el-col>
<el-col :span="6"
><div class="grid-center">
<el-select v-model="value" placeholder="el-select">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
</el-select></div
></el-col>
<el-col :span="6"
><div class="grid-right">
<el-select v-model="value" placeholder="el-select">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
</el-select></div
></el-col>
</el-row>
<span slot="footer" class="dialog-footer">
<el-button @click="fullDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="fullDialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
...
data() {
return {
fullDialogVisible: false
}
}
...
</script>以上代码就是为了写一个弹框,且弹框内有左中右三个下拉框,来显示下拉框是否位置正常。
全文重点
打开examples\main-vue\src\views\Vue2-sub.vue此文件,写入:
<template>
<WujieVue width="100%" height="100%" name="vue2" :url="vue2Url" :plugins="plugins"></WujieVue>
</template>
<script>
...
data() {
return {
plugins: [
{
// 在子应用所有的css之前
cssBeforeLoaders: [
// 强制使子应用body定位是relative
{ content: "body{position: relative !important}" },
],
},
{
jsLoader: (code) => {
// 替换popper.js内计算偏左侧偏移量
var codes = code.replace(
"left: elementRect.left - parentRect.left",
"left: fixed ? elementRect.left : elementRect.left - parentRect.left"
);
// 替换popper.js内右侧偏移量
return codes.replace("popper.right > data.boundaries.right", "false");
},
},
],
}
}
...
</script>按以上操作则可以实现官网例子内的弹框不在偏移。且不论下拉框是何种定位都能实现完美位置。
综上所述
你只需更改主应用的plugins即可修复弹框偏移问题;按照5所述,修改即可。(费了大量的时间和精力,一直在寻找一个完美且傻瓜式的解决办法,最终还是调试源码,找到此办法。github上解决此问题的人都是各种技巧,但我们只需要最朴素且简单见效的办法。)
最终实现效果展示:

(弱弱的问一句):如果解决了你的问题,可否到(小程序/app)拼夕夕上搜 店铺 “琼肴食货”, 进店来一单。。。

以上就是 微前端下element-ui弹框偏移问题解决的详细内容,更多关于 微前端下element-ui弹框偏移问题解决的资料请关注脚本之家其它相关文章!
