我有一个组件,需要通过ajax调用提取一些数据。该组件被称为罚款,并且数据在ajax调用中返回,但是我无法将其分配给模板中的数据?
<template>
<div class="class-hero" id="dashboard-hero" :style="{ 'background-image': 'url(' + last.content_image + ')' }">
<div class="class-hero-overlay"></div>
<div class="class-hero-container">
<h1> {{ last.content_name }}</h1>
<p> {{ last.content_description }} </p>
<div class="class-stat">
<div id="classesCirle" class="hero-class-progress"></div>
<p>Modules</p>
</div>
<div class="class-stat">
<div id="studentsCircle" class="hero-class-progress"></div>
<p>students</p>
</div>
<div class="class-stat">
<div id="tasksCirle" class="hero-class-progress"></div>
<p>tasks</p>
</div>
<a :href="'/all-classes/' + last.content_name + '/' " class="button-resume"><p>Resume</p></a>
</div>
</div>
</template>
<script>
module.exports = {
data: function() {
return {
last:[]
}
},
mounted: function() {
axios.get('/custom_api/api_home_get.php?', {
params: {
ID: 14
}
})
.then(function (response) {
this.last = response.data.currentCourses[0];
console.log(response.data.currentCourses[0]);
})
.catch(function (error) {
console.log(error);
});
}
}
</script>
这不可能吗?如何将数据
last
设置为在mounted
中进行的ajax调用 最佳答案
this
函数中的then
与组件的this
不同,因为在Javascript上,this
关键字已绑定到其父函数。
您可以通过here和this示例了解有关它的更多信息。
您可以通过以下几种方式修复它:
1-使用Function原型的bind
方法。这会将您的外部this
与本地this
绑定在一起。
axios.get('/custom_api/api_home_get.php?', {
params: {
ID: 14
}
})
.then(function (response) {
this.last = response.data.currentCourses[0];
console.log(response.data.currentCourses[0]);
}.bind(this))
.catch(function (error) {
console.log(error);
});
2-使用ES6箭头功能(将产生与上述相同的效果)
axios.get('/custom_api/api_home_get.php?', {
params: {
ID: 14
}
})
.then(response => {
this.last = response.data.currentCourses[0];
console.log(response.data.currentCourses[0]);
})
.catch(function (error) {
console.log(error);
});