Responsive form for element-plus
Set form attributes size
and label-position
to computed properties.
<el-form :model="formModel" label-width="auto" :size="formSize" :label-position="labelPosition">
Add listener to watch window width on mounted, calculate formSize
and labelPosition
based on windowWidth
.
let Main = {
data () {
return {
windowWidth: window.innerWidth
};
},
computed: {
formSize () {
return this.windowWidth <= 540 ? 'mini' : (this.windowWidth <= 960 ? 'small' : 'medium');
},
labelPosition () {
return this.windowWidth <= 540 ? 'top' : 'right';
}
},
mounted () {
// watch window width
window.addEventListener('resize', () => {
this.windowWidth = window.innerWidth;
});
}
};
const app = Vue.createApp(Main);
app.use(ElementPlus);
app.mount('#app');
Alternatively, if form size is not concerned, use CSS @media
to change label position only.
/* responsive form */
.responsive .el-form-item__label {width: 120px;}
.responsive .el-form-item__content {margin-left: 120px; margin-right: 20px;}
@media screen and (max-width:540px){
.responsive .el-form-item__label {margin: 0 10px; text-align: left;}
.responsive .el-form-item__content {margin: 0 10px; clear: left;}
}
<div class="responsive">
<el-form :model="formModel">