0.0.2 • Published 2 years ago
@solidk-tech/schema-to-component v0.0.2
Schema to Component
This is a helper library used to make it easier to render components on you project.
Example of usage with multiples fields.
// .src/classes/MyModel.ts
class MyModel extends MySchema {
email: string | null = "";
password: string | null = "";
}
// .src/schema/MySchema.ts
import { MyModel } from "./MyModel";
export class MySchema extends Schema {
translateFrom = (fieldName: string) => fieldName.toLocaleUpperCase();
readonly fieldSet: FieldSet<MyModel> = {
email: (schema): FieldComponent<MyModel, any> => ({
component: "input",
props: {
id: "id-email",
name: "name-email",
type: "text",
placeholder: "This is an input",
className: "my-component-class",
value: schema.model.email,
onInput: (event: any) => (schema.model.email = event?.target.value),
},
}),
password: (schema): FieldComponent<MyModel, any> => ({
component: "input",
props: {
id: "id-password",
name: "name-password",
type: "password",
placeholder: "*****",
className: "my-component-class",
onInput: (event: any) => (schema.model.password = event?.target.value),
},
}),
};
}
// .src/App.vue
<script setup lang="ts">
import { reactive } from "vue";
import { MyModel } from "./classes/MyModel";
const data = reactive(new MyModel());
function clg(val: any) {
console.log(val);
}
</script>
<template>
<form @submit.prevent="clg">
<RenderSchema
v-for="(item, index) in data.allFields"
:key="index"
:model="data"
:fieldName="item"
/>
<button type="submit">Send</button>
</form>
</template>
Alternative you can render only a specific field of the class.
// .src/App.vue
<script setup lang="ts">
import { reactive } from "vue";
import { MyModel } from "./classes/MyModel";
const data = reactive(new MyModel());
function clg(val: any) {
console.log(val);
}
</script>
<template>
<form @submit.prevent="clg">
<RenderSchema :model="data" :fieldName="email" />
<RenderSchema :model="data" :fieldName="password" />
<button type="submit">Send</button>
</form>
</template>
This is how the component is gone look like:
<!-- index.html Rendered -->
<div id="app">
<form>
<input
id="id-email"
name="name-email"
type="text"
placeholder="This is an input"
class="my-component-class"
/><input
id="id-password"
name="name-password"
type="password"
placeholder="*****"
class="my-component-class"
/><button type="submit">Send</button>
</form>
</div>