重构ElementUI解决DatePicker日期选择组件修改父组件placement参数问题
When using el-date-picker , the browser console would send a vue warning:
... Prop being mutated: "placement" found in <ElDatePicker> ...
开发环境
node | 14.16.1 |
---|
npm | 8.18.0 | vue-cli | 2.9.6 | vue | 2.5.2 |
解决方案
The problem arose because the latest element-ui (v2.15.9) changes vue props placement in the child component date-picker , which is not allowed in vue since the value will be overwritten whenever the parent component re-renders. The source code causing this issue seems like:
const NewPopper = {
props: {
placement: Popper.props.placement,
},
};
const PLACEMENT_MAP = {
left: 'bottom-start',
center: 'bottom',
right: 'bottom-end'
};
export default {
created() {
this.popperOptions = {
boundariesPadding: 0,
gpuAcceleration: false
};
this.placement = PLACEMENT_MAP[this.align] || PLACEMENT_MAP.left;
this.$on('fieldReset', this.handleFieldReset);
},
}
Note that this.placement = PLACEMENT_MAP[this.align] || PLACEMENT_MAP.left; modified props placement . We resolve the problem by just simply muting this code according to #21943.
We use patch-package to make and keep fixes to npm dependencies:
npm i patch-package -D --legacy-peer-deps
Download element-ui releases v2.15.9 on GitHub, make the above modification to your downloaded git repo and rebuild element-ui to overwrite the lib folder in node_modules/element-ui :
cd /path/to/your/repo
npm install --legacy-peer-deps
vim packages/date-picker/src/picker.vue
npm run dist
mv -f /path/to/your/repo/lib /path/to/your/project/node_modules/element-ui/lib
Attention! The version of dependency node-sass in element-ui git repo must match your node version. Node version support policy tells you about that. Modify package.json in your repo so that no error would be thrown.
Then we fix this bug in our dependencies after replacing the lib folder of element-ui, and run:
npx patch-package element-ui
If this is the first time you’ve used patch-package , it will create a folder called patches in the root dir of your app. Inside will be a file called element-ui+2.15.9.patch , which is a diff between normal old package name and your fixed version. Commit this to share the fix with your team:
git add patches/element-ui+2.15.9.patch
git commit -m "fix picker.vue in element-ui@2.15.9"
In package.json , make the following change to make sure the modification will be kept when reinstall the dependency:
"scripts": {
+ "postinstall": "patch-package"
}
|