问题
在编写前端功能时发现两个问题,由于要发送post json格式内容,修改了 axios 发送请求的脚本,导致在使用 Message 提示框,和 Loading 加载功能时,作用域出现了问题
第一版代码
export default {
data() {
return {
data_1: '',
data_2: '',
loading: false
}
},
methods: {
addBtn() {
this.loading = true
var params = {
'data_1': this.data_1,
'data_2': this.data_2
}
axios.post('url', {
jsonData: JSON.stringify(params)
})
.then(function(response){
if(response.data.errcode == 0){
this.$message({
message: 'Succeed',
type: 'success'
});
}
else{
this.$message({
message: response.data.error,
type: 'error'
});
}
this.loading = false
},function(res){});
}
}
}
此时出现两个问题
- 问题1: 报错提示未定义 this.$message
- 问题2: loading 加载中状态未消失
以上两个问题都是由于作用域导致,在function 函数中,this的内容发生了变化导致无法使用函数外的message、loading 属性
初步优化
查询资料后,将 this.$message 部分修改为 Vue.prototype.$message,问题1成功解决
import Vue from 'vue'
……
Vue.prototype.$message({
message: 'Succeed',
type: 'success'
});
……
但此时没有根本的解决作用域问题,请教了前端大佬后,推翻上述修改方法,直接将 then 后面的函数定义由 .then(function(response){}) 格式修改为 .then((response) => {});,修改后 this 指向内容不变,可以直接使用第一版代码中的 this.$message 和 this.loading 调用方式
methods: {
addBtn() {
this.loading = true
var params = {
'data_1': this.data_1,
'data_2': this.data_2
}
axios.post('url', {
jsonData: JSON.stringify(params)
})
.then((response) => {
if(response.data.errcode == 0){
Vue.prototype.$message({
message: 'Succeed',
type: 'success'
});
}
else{
Vue.prototype.$message({
message: response.data.error,
type: 'error'
});
}
this.loading = false
},function(response){});
},
}
进一步优化后的最终方案
进一步经过大佬指点后,了解到可以使用 async 和 await 方法异步执行 post 请求,并将返回结果赋值到 response 变量中,可以继续按照同步方式编写代码,使代码看起来更加美观
methods: {
async addBtn() {
this.loading = true
var params = {
'data_1': this.data_1,
'data_2': this.data_2
}
const response = await axios.post('url', {
jsonData: JSON.stringify(params)
})
if(response.data.errcode == 0){
this.$message({
message: 'Succeed',
type: 'success'
});
}
else{
this.$message({
message: response.data.error,
type: 'error'
});
}
this.loading = false
},
}
在Vue.js前端开发中,遇到axios请求后this.$message和this.loading功能失效的问题。通过分析发现,作用域变化导致报错。首先尝试通过Vue.prototype.$message修复问题1,但未解决根本。然后,采用.then((response) => {})箭头函数保持this指向,成功修复问题。最后,学习使用async/await进行异步请求,优化代码结构,实现了更优雅的解决方案。


2206

被折叠的 条评论
为什么被折叠?



