Vue3+Axios+Laravel中增改方法调用getData失效的原因
问题:新增/更新后调用
getData无效,但删除时正常的原因及解决方法 核心原因:this指向不一致
你遇到的问题根源在于axios回调函数的this指向不同:
- 删除方法
deleteData中使用了箭头函数作为回调,箭头函数不会绑定自身的this,会继承外层作用域的this(也就是Vue实例),所以this.getData()能正确调用。 - 新增
addNumbertype和更新updateData方法中使用了普通function作为回调,普通函数会绑定自身的this,此时this指向的是axios回调的上下文,而非Vue实例,导致this.getData()找不到对应方法,自然无法触发数据刷新(打开浏览器控制台应该能看到Uncaught TypeError: this.getData is not a function的报错)。
解决方法
有两种常用的修复方式:
方式1:将回调改为箭头函数
把addNumbertype和updateData里的axios回调替换为箭头函数,让this继承外层Vue实例的上下文:
// 新增方法修改示例 addNumbertype() { axios.post('/add', this.add_numbertype) .then((response) => { // 改成箭头函数 if (response.status === 200) { document.getElementById("add-form").reset(); $('#createModal').modal('hide'); Swal.fire( 'Add', 'New record added Successfully', 'success' ) this.getData(); // 此时this指向Vue实例 } else { alert("error"); } }).catch((error) => { // catch也建议同步修改 console.log(error.response); }) } // 更新方法同理修改回调为箭头函数 updateData(id) { axios.post('/update/' + id, this.add_numbertype) .then((response) => { // 改成箭头函数 if (response.status === 200) { $('#updateModal').modal('hide'); document.getElementById("update-form").reset(); Swal.fire( 'Update', 'New record updated Successfully', 'success' ); this.getData(); } }).catch((error) => { console.log(error.response); }) }
方式2:提前保存Vue实例的this到变量
在方法开头将Vue实例的this存入变量,回调中用该变量调用方法:
// 新增方法修改示例 addNumbertype() { const vm = this; // 保存Vue实例的this axios.post('/add', this.add_numbertype) .then(function(response) { if (response.status === 200) { // ...其他逻辑 vm.getData(); // 使用vm调用方法,vm指向Vue实例 } }) } // 更新方法同理 updateData(id) { const vm = this; axios.post('/update/' + id, this.add_numbertype) .then(function(response) { if (response.status === 200) { // ...其他逻辑 vm.getData(); } }) }
修改后重新测试,新增/更新操作完成后,数据列表应该会自动刷新,无需页面重载。
内容的提问来源于stack exchange,提问作者Cookie
相关产品推荐
相关产品推荐

