My expertise lies primarily in React, and I'm now exploring the Vue-centric approach to achieve the following:
I want to enhance this component: , so that the label-position
is set to top
on mobile devices and left
on desktop. However, I'm not sure how to pass the properties of the component to the element.
This is the pseudo-code I have come up with so far:
<template>
<el-form v-bind="formProps" :label-position="labelPosition">
<slot />
</el-form>
</template>
<script>
import Vue from 'vue';
export default Vue.component('el-form-responsive', {
data() {
return {
labelPosition: 'top',
};
},
created() {
this.mobileQuery = window.matchMedia('(max-width: 720px)');
this.onMobileQueryTrigger(this.mobileQuery);
this.mobileQuery.addListener(this.onMobileQueryTrigger);
},
beforeDestroy() {
this.mobileQuery.removeListener(this.onMobileQueryTrigger);
},
methods: {
onMobileQueryTrigger(query) {
if (query.matches) {
console.log('is mobile');
this.$data.labelPosition = 'top';
} else {
this.$data.labelPosition = 'left';
console.log('is not mobile');
}
},
},
});
</script>
As far as I know, v-bind
does not transfer events and directives. Therefore, the following code does not achieve what I intend:
<el-form-responsive
:formProps="{
class: 'form',
':model': 'formValues',
'status-icon': true,
':rules': 'rules',
ref: 'form',
'label-width': 'auto',
'@submit.native.prevent': 'submitForm'
}"
>
The above method seems cumbersome and inelegant. I would prefer a simpler approach like this:
<el-form-responsive
class="form"
:model="formValues"
status-icon
:rules="rules"
ref="form"
label-width="auto"
@submit.native.prevent="submitForm"
>
However, I am uncertain about how to spread these props onto the el-form
element. Is there a more Vue-centric way to achieve this? It seems like a fundamental task, so maybe I am missing something.