如何通过jQuery AJAX调用更新VueJS实例的数据? [英] How to update data of a VueJS instance from a jQuery AJAX call?
问题描述
我有一个带有一些数据的VueJS实例:
I have a VueJS instance with some data :
var vm = new Vue({
el: '#root',
data: {
id: '',
name: {
firstname: "",
lastname: "",
country: "",
valueset: false
},
// ...
在我的HTML中,我也有:
In my HTML, I also have :
<input class="id" type="text" size="4" maxlength="4" v-model.lazy="id" v-on:change="create_casenr">
因此,填写完此字段后,将触发我的实例的方法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);
})
// ...
会发生什么:
-
create_casenr
在字段更改时被调用(确定) - AJAX调用成功进行,我在控制台上看到
data
和this.name
的预期输出(确定) - 但但
name
在VueJS实例中未更新.
create_casenr
is called upon the change in the field (OK)- the AJAX call goes through successfully, I see the expected output on the console for both
data
andthis.name
(OK) - but
name
is not updated in the instance of VueJS.
我可以看到它没有被更新,因为依赖它的代码的其他部分看不到它.我还检查了VueJS Chrome插件,正确设置了所有变量(包括id
),除了name
.
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
.
通过jQuery AJAX调用修改VueJS实例的数据时,是否有一种特定的方法?
推荐答案
您的AJAX成功处理程序中出现范围问题this.name
.
You have a scope issue of this.name
in your AJAX success handler.
内部的this.name
与Vue组件中的this.name
不同.因此,不会在Vue组件中设置您的名字.
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;
});
相似的答案: https://stackoverflow.com/a/40200989/654825
有关箭头功能的更多信息: https://developer. mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
More info on Arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
这篇关于如何通过jQuery AJAX调用更新VueJS实例的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!