Why I can\'t bind the object properties in Vue? The object addr
is not reactive immediately, but test
is reactive, how come? In this case, how shou
As per my comments, there are several things that you want to consider:
addr
is reactive, any properties added to addr
that is not done when it is declared will make it non-reactive. Refer to the VueJS docs for more details: https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveatsv-for
to iteratively inject input fields based on the number of input fields you have.Now back to the second point, if you know what fields addr
will have, you can simply declare it in your app. We create a new updateFormData
method, which is called by the component:
data: {
addrFields: ['contactNum', ...],
addr: {},
test: ""
},
methods: {
updateFormData: function(id, value) {
this.$set(this.addr, id, value);
}
}
We can still store your form data in the addr
object, which will be updated by the updateFormData
method based on the received payload using .$set(). Now, we can then create a custom Vue component for your input element.
In the example below, the component will iterate through all your addrFields
, and pass down the addrField
as a prop using :id="addrField"
. We also want to make sure that we capture the custom-named updated
event emitted from within the component.
The template can look something like the following. It simply uses the id
prop for both its id
, name
, and placeholder
attribute (the latter for easy identification in the demo). We bind the @change
and @input
events, forcing it to trigger the updated
callback:
In the component logic, you let it know that it will receive id
as a prop, and that it should emit an inputUpdated
event using $.emit(). We attach the ID and value as payloads, so that we can inform the parent what has updated:
var myInput = Vue.component('my-input', {
template: '#my-input',
props: {
id: {
type: String
}
},
methods: {
updated: function() {
this.$emit('inputUpdated', this.id, this.$el.value);
}
}
});
With the code above, we have a working example. In this case, I have created an arbirary array of input fields: contactNum
, a
, b
, and c
:
var myInput = Vue.component('my-input', {
template: '#my-input',
props: {
id: {
type: String
}
},
methods: {
updated: function() {
this.$emit('updated', this.id, this.$el.value);
}
}
});
var vm = new Vue({
el: '#app',
data: {
addrFields: ['contactNum', 'a', 'b', 'c'],
addr: {},
test: ""
},
methods: {
updateFormData: function(id, value) {
this.$set(this.addr, id, value);
}
}
});
addr: {{addr}}
addr.contactNum: {{addr.contactNum}}
test: {{test}}