I have a VueJS instance with some data :
var vm = new Vue({
el: '#root',
data: {
id: '',
name: {
firstname: "",
lastname: "",
country: "",
valueset: false
},
// ...
In my HTML, I also have :
<input class="id" type="text" size="4" maxlength="4" v-model.lazy="id" v-on:change="create_casenr">
Therefore after filling up this field, the method create_casenr
of my instance is triggered.
create_casenr: function(event) {
// update the full name of user
$.ajax({
url: 'http://elk.example.com:9200/users/user/' + this.id
})
.done(function(data) {
console.log(data);
this.name = data._source;
this.name.valueset = true;
console.log(this.name);
})
// ...
What happens is that :
create_casenr
is called upon the change in the field (OK)data
and this.name
(OK)name
is not updated in the instance of VueJS.I can see it is not updated because other parts of my code which rely on it do not see it; I also checked with the VueJS Chrome add-on and all the variables are correctly set (including id
), except for name
.
Is there a specific way I should address the data of a VueJS instance when modified via a jQuery AJAX call?
You have a scope issue of this.name
in your AJAX success handler.
The this.name
inside is not the same as this.name
in your Vue component. So your name is not getting set in the Vue component.
You may use arrow functions to get around this issue:
$.ajax({
url: 'http://elk.example.com:9200/users/user/' + this.id
}).done(data => {
this.name = data._source; // 'this' points to outside scope
this.name.valueset = true;
});
Similar answer: https://stackoverflow.com/a/40200989/654825
More info on Arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With