问题:
点击登陆之后通过后端验证之后跳转到首页,在渲染时同时加载ajax的数据为空。
//创建一个Vue对象
let vm = new Vue({
el: '#app',
data: {
tableData: [],
loginName:''
}, methods: {
open() {
this.$confirm('此操作将会注销账号, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// window.location='login.html'
$.ajax({
url:'cancel',
type:'get',
dataType: 'json',
success:(result)=>{
if(result.code == 800){
setTimeout(()=>{window.location='login.html'},1200);
}
}
})
this.$message({
type: 'success',
message: '注销成功!'
});
}).catch(() => {
this.$message({
type: 'info',
message: '已取消注销'
});
});
}
},
created:function(){
//Vue对象创建的时候向servlet请求数据
$.ajax({
url:'index',
type:'get',
dataType:'json',
success:(result)=>{
if(result.code == 1003) {
// userName = result;
console.log(result.data.customer)
console.log(result.data.customers)
//获取所有数据
this.tableData = result.data.customers;
//获取登录人
this.loginName = result.data.customer.name
}else{
window.location='login.html';
}
},
error:function (result) {
console.log(result)
}
});
}
});
分析:
个人尝试控制台打印了一下Vue中数据的值,当页面渲染加载的时候vue里面的值已经创建,而tableData: [],没有取到值,简单的上网查了一下这是vue的生命周期的问题。
解决方案:
1、将ajax改为同步请求并放在vue对象创建之前(不推荐)
2、像上面代码一样将ajax请求放到Vue的**created:function(){}**中, 这样就会在加载或渲染的同时去请求数据最终显示数据,记得要使用this关键字。(推荐)
3、在界面加载的时候给整个窗口绑定事件去让ajax请求。(不推荐)