从子方法中操作 vue.js 数据参数 [英] manipulate vue.js data parameter from within sub method
问题描述
我知道我可以通过使用 this.variable_name
在方法中更改 vue 数据值的值.但是,当我尝试从带有子方法的方法中执行此操作时(因为我正在发出 ajax 请求),我收到了 undefined
错误.
I know that I can change the value of a vue data value from within a method by using this.variable_name
. But when I'm trying to do this from within a method with a sub-method (because I'm making an ajax request) I am getting an undefined
error.
我有类似的东西
var myvue = new Vue({
name: "MyVue",
el: '#my-vue-id',
data: {
fields: field_list // this is set in another js method elsewhere
},
methods: {
reject: function (index, objectid) {
if (confirm("Are you sure?")) {
$.get("/reject/" + objectid, function (data) {
if (data.success == true) {
$("#" + objectid).fadeOut(400, function() {
this.field_list.splice(index, 1);
});
} else {
alert('Failed to delete.');
}
});
}
}
}
});
我还尝试在 $.get
方法中设置 var self = this;
,然后尝试拼接 self.field_list
但在两者中如果我收到错误 Cannot read property splice of undefined
I also tried setting var self = this;
within the $.get
method, then trying to splice self.field_list
but in both cases I get an error Cannot read property splice of undefined
编辑,因为我可能不清楚 - 正在填充 field_list
.如果我要在 ajax 函数之外执行 this.field_list.splice
,它工作正常.问题只是如何使用 vue 方法访问外部作用域.
EDIT since I may have been unclear-- the field_list
is being populated. If I were to do this.field_list.splice
outside the ajax function, it works fine. The issue is just how to access external scope from with the vue methods.
推荐答案
回调函数在调用时不会将您的 Vue 实例作为其上下文 (this
).为回调使用箭头函数,或将 this
保存到变量并使用它.
A callback function does not get your Vue instance as its context (this
) when it is called. Use arrow functions for your callbacks, or save this
to a variable and use that.
这篇关于从子方法中操作 vue.js 数据参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!