With Vue.js you can you bind form input to a property:
https://v2.vuejs.org/v2/guide/forms.html
I am working on a project where I ‘dynamically’ generate a form though. Here the v-model bindings are just attributes that are being set based on the name that an input has.
The problem though is that I am left wondering how to properly get these v-model bindings. So far all I have see is people manually setting a property on their Vue instance for the binding:
new Vue({ el: '...', data: { checkedNames: [] } })
Is it possible to somehow grab all of the v-model
bindings though without setting up the data properties manually?
When creating a dynamic form with a variation an dynamic number of fields this would help out a lot.
I guess one option is simply retrieving the name atributes from the input with javascript but I am hoping there might be something in place already since v-model
is probably calling a setter that might already be known in the Vue instance.
Reworked the example from the answer:
https://jsfiddle.net/yMv7y/2477/
Advertisement
Answer
According to the official documentation:
it’s possible to add reactive properties to a nested object using the
Vue.set(object, key, value)
method.
This means that your starting data
can be something like:
{ customForm: [], values: {} }
Let’s assume customForm
is an array of field objects that describe a bunch of fields in your custom form. It’s empty at the beginning because you say your form will be created dynamically.
Once you generate that dynamic data, all you need to do is assign it to customForm
and loop through it to add reactive properties with the aforementioned Vue.set
method.
Here’s a JSFiddle with an example. I’m using this.$set
, but that’s just an alias for Vue.set
.