I'm trying to build a re-usable component to deal with submitting forms via AJAX using Vue.js. Ideally, what I want to do is have a generic component that can be used in place of a HTML form
element, in that may contain an unknown set of form elements such as input
, select
, textarea
and so on.
I have got the following code for my component which is named ajax-form
:
<template>
<form class="form" :action="action" :method="method" v-on:submit.prevent="ajaxSubmit">
<slot></slot>
</form>
</template>
<script>
module.exports = {
props: {
action: {
required: true,
type: String
},
method: {
default: 'post',
required: false,
type: String
}
},
data() {
return {
formData: {}
}
},
methods: {
ajaxSubmit() {
// Do ajax
}
}
}
</script>
And in my HTML, I would have something like the following:
<ajax-form action="http://example.com/do/something">
<input name="first_name" type="text">
<textarea name="about_you"></textarea>
</ajax-form>
What I would ideally like to happen is have all of the form elements that are placed inside my component using it's slot to be mapped to the data.formData
property in my Vue component instance. So in this case, the data
property would look like:
data: {
formData: {
first_name: '',
about: ''
}
}
If I was to add another field to the component in my HTML, I would expect that to also be mapped to the Vue instance's data
property.
Is there a way I can achieve this? Is there a way that I can tell Vue, when putting my form elements into the component via the slot, that I want this element to be mapped to something in the component's data
?
I have tried adding v-model
and v-bind
on each form element to see if it that would somehow pass the data into the component's data:
<ajax-form action="http://example.com/do/something">
<input name="first_name" type="text" v-model="formData.first_name">
</ajax-form>
However, Vue complains that reactive data properties must be declared before they're used in the template:
[Vue warn]: Property or method "formData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
mounted
(vuejs.org/v2/api/#mounted) method to get a reference to the DOM element that Vue creates, and then iterate over it's children (using jQuery?) and add reactive properties tothis.data
viaVue.set
(vuejs.org/v2/api/#Vue-set). – PatrickSteeledata
. Your suggestion assumes that I know what the data etc. is going to be ahead of time. – Jonathon