Vue.js子方法内操作data参数出现undefined错误求助
解决Vue.js中Ajax回调里
this指向undefined的问题 这个问题太常见啦!你遇到的undefined错误,核心原因是在jQuery Ajax的回调函数里,this的上下文已经变了——不再指向你的Vue实例myvue,而是指向了Ajax请求相关的对象,所以自然找不到data里的fields变量。
我给你几个简单好用的解决方案,直接结合你的代码来改:
方案1:提前保存Vue实例的this到变量
这是最经典的处理方式,把外部的Vue实例引用存下来,在回调里用这个变量代替this:
var myvue = new Vue({ name: "MyVue", el: '#my-vue-id', data: { fields: field_list }, methods: { reject: function (index, objectid) { if (confirm("Are you sure?")) { // 把Vue实例的this存到vm变量里 const vm = this; $.get("/reject/" + objectid, function(response) { // 这里用vm就能访问到data里的fields了 // 比如更新fields: vm.fields = [...vm.fields.filter(item => item.id !== objectid)]; }); } } } })
方案2:使用箭头函数(ES6+)
箭头函数不会创建自己的this,它会继承外部作用域的this,也就是你的Vue实例,代码更简洁:
var myvue = new Vue({ name: "MyVue", el: '#my-vue-id', data: { fields: field_list }, methods: { reject: function (index, objectid) { if (confirm("Are you sure?")) { // 箭头函数直接继承外部的this(Vue实例) $.get("/reject/" + objectid, (response) => { this.fields = [...this.fields.filter(item => item.id !== objectid)]; }); } } } })
方案3:用bind()绑定this
可以手动把回调函数的this绑定到Vue实例上,适合不能用箭头函数的场景:
var myvue = new Vue({ name: "MyVue", el: '#my-vue-id', data: { fields: field_list }, methods: { reject: function (index, objectid) { if (confirm("Are you sure?")) { $.get("/reject/" + objectid, function(response) { this.fields = [...this.fields.filter(item => item.id !== objectid)]; }.bind(this)); // 绑定this到Vue实例 } } } })
个人最推荐方案2,代码更清爽,只要你的项目支持ES6语法就行;如果是老项目,方案1兼容性更好。
内容的提问来源于stack exchange,提问作者user101289




