Skip to content

Instantly share code, notes, and snippets.

@razbakov
Created February 7, 2024 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save razbakov/484eed5d6286e33bccb66f2366567b02 to your computer and use it in GitHub Desktop.
Save razbakov/484eed5d6286e33bccb66f2366567b02 to your computer and use it in GitHub Desktop.
Vue Form Component
<template>
<form @submit.prevent="submit">
<slot />
</form>
</template>
<script>
import Vue from 'vue'
import { onMounted, ref } from '@nuxtjs/composition-api'
export default {
name: 'WdForm',
setup(props, { slots, emit }) {
const fields = ref([]);
const errors = ref({});
const valid = ref(true);
function submit() {
if (!validate()) {
return
}
emit('submit', props.value)
}
function validate() {
console.log('validate', fields.value)
errors.value = {}
valid.value = true
for (const field in fields.value) {
console.log('field.rule', field.rule)
if (
field.rule==="required" &&
!this.value[field.name]
) {
Vue.set(errors, field.name, 'form.required')
valid.value = false
}
}
return valid.value
}
onMounted(() => {
const children = slots.default();
for (const child of children) {
if (!child?.componentOptions?.propsData) {
continue;
}
fields.value.push(child.componentOptions.propsData);
}
})
return {
fields,
submit
}
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment