为了在页面加载后从服务器加载一些数据,我有以下脚本:
<script>
export default {
data() {
return {
imageDirectory: "../../images/",
fileName: "img",
extension: ".png",
products:
[
{
name: 'loading data',
imageUrl: require("../../assets/t1.png")
}
]
}
},
name: "ProductList",
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
$.ajax({
type: "GET",
timeout: 1200000,
url: 'api/test',
contentType: "application/json",
dataType: "text",
success: function (data) {
window.alert(data);
this.products = [{
name: 'success' + 'test',
imageUrl: require("../../assets/t1.png")
}] },
error: function (data) {
this.products = [{
name: 'failed' + 'test',
imageUrl: require("../../assets/t1.png")
}]
}
});
}
}
}
</script>
现在当我运行它时,我确实得到了一个警告窗口,显示它确实获取了数据,但是,它实际上并没有设法更新有问题的对象(产品名称仍然是加载数据而不是成功测试)。如果我移动代码
this.products = [{ name: '成功' + '测试', imageUrl: require("../../assets/t1.png") }]
像这样进入 created: function()
:
created: function () {
this.products = [{
name: 'success' + 'test',
imageUrl: require("../../assets/t1.png")
}]
this.fetchData();
}
它确实更新了数据。所以这意味着获取数据的代码是准确的,更新数据的占位符也是有效的,那么为什么数据没有更新呢?
(注意更新数据的代码是一个占位符)。
最佳答案
在您的 fetchData 函数中,您在 $.ajax() 中使用了“this”关键字,这可能会使编译器混淆您所引用的对象,所以为什么不试试这个:
fetchData: function () {
let app = this;
$.ajax({
type: "GET",
timeout: 1200000,
url: 'api/test',
contentType: "application/json",
dataType: "text",
success: function (data) {
window.alert(data);
app.products = [{
name: 'success' + 'test',
imageUrl: require("../../assets/t1.png")
}] },
error: function (data) {
app.products = [{
name: 'failed' + 'test',
imageUrl: require("../../assets/t1.png")
}]
}
});
}
关于javascript - 如何获取数据更新数据以在获取数据后显示在vue中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52588257/