使用vue框架,ajax发送请求,渲染页面进不去
# 问题描述
使用vue框架,利用ajax发送请求,前端利用console.log可以打印出来值,但是在页面渲染时,一直渲染不进去。如下所示:
代码块:
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data:{
tableData: [{
id:"",
workNumber:"123",
name:"123",
email:"123",
professional:"123"
}],
search: ''
},
created:function(){
// 查询教师基本信息
this.query1();
},
methods:{
/* 查询教师基本信息 */
query1(){
$.ajax({
cache:true,
type:"post",
url:"teacherServlet",
data:{"action":"query"},
dataType:"json",
async:false,
error:function(req){
alert("发送请求失败");
},
success:function(res){
console.log(res);
this.tableData = res.data;
}
});
}
}
});
</script>
解决
结果发现,因为ajax内容中的this并不是指向vue这个对象了,所以先保存一下this,来使用tableData
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data:{
tableData: [{
id:"",
workNumber:"123",
name:"123",
email:"123",
professional:"123"
}],
search: '',
},
created:function(){
// 先把this保存起来
var _self = this;
// 查询教师基本信息
this.query1();
$.ajax({
cache:true,
type:"post",
url:"teacherServlet",
data:{"action":"query"},
dataType:"json",
async:false,
error:function(req){
alert("发送请求失败");
},
success:function(res){
console.log(res);
_self.tableData = res.data;
console.log(_self.tableData[3].name);
// window.location.href="teacherInfo.html?dataList="+res.data;
}
});
},
methods:{
/* 查询教师基本信息 */
query1(){
}
}
});
渲染成功
存在问题
当我的query1方法放在methods里时,页面是渲染不出来,只能将ajax请求放在created中,才可以加载出来,如上所示。
测试的时候设置了同步aysnc为true,也没有用,页面同样渲染不出来。我用的this.query1(),这个this同样也是指向这个vue对象的,但是值是渲染不进去的。这一点不明白为什么。希望被指点,谢谢!