For some time now, I have been attempting to develop a Vue.js-based "customizable form template". The approach I envisioned involves:
- Developing a "custom-form" component that accepts a
vueForm
prop and displays a form. ThevueForm
prop is structured as an object with distinctfields
anderrors
keys. - Creating a "custom-input" component that takes multiple props, including
value
(for v-model) anderrors
... both of which are included in the previously mentionedvueForm
object
The issue I'm facing is the inability to access the vueForm
object passed as a prop in the custom-form
component FROM my custom-input
component :(. I've experimented with data addition, provide/inject usage, and more, but haven't had any success yet.
I would greatly appreciate any assistance :)
Thank you
Below is a snippet of the code:
COMPONENTS
// PARENT COMPONENT
Vue.component("custom-form", {
props: {
vueForm: Object,
},
template:
`<form :id="vueForm.id" :method="vueForm.method" action="">
<slot></slot>
</form>`,
});
// CHILD COMPONENT
Vue.component("custom-input", {
props: {
name: String,
type: String,
placeholder: String,
icon: String,
value: [String, Number, Date],
errors: Array,
},
template:
`<div class="field">
<div class="control has-icons-left has-icons-right">
<span class="icon is-small is-left">
<i :class="icon"></i>
</span>
<input
class="input"
:type="type"
:name="name"
:placeholder="placeholder"
v-on:input="$emit('input', $event.target.value)"
>
<span class="icon is-small is-right" v-if="errors.length">
<i class="fas fa-exclamation-triangle"></i>
</span>
<p class="help is-danger" v-for="message in errors">
{{message}}
</p>
</div>
</div>`,
});
VUE
var mainVue = new Vue({
el: "main",
data: {
loginTab: true,
authForm: {
id: "user-form",
method: "POST",
errors: {
non_field_errors: [],
email: [],
password: [],
confirm_password: [],
},
fields: {
email: "",
password: "",
confirm_password: "",
},
},
},
});
HTML
<custom-form :vue-form="authForm"> <!-- Passing authFrom as our vueForm prop -->
<custom-input
name="email"
type="email"
placeholder="Email"
icon="fas fa-envelope"
:value="vueForm.fields.email" <!-- vueForm is not defined :( -->
:errors="vueForm.errors.email" <!-- vueForm is not defined :( -->
></custom-input>
<button
class="button is-primary"
@click.prevent="submitForm"
>
<span class="icon is-small">
<i class="fas fa-check"></i>
</span>
<span>{% trans "Submit" %}</span>
</button>
</custom-form>