我使用日期选择器并使用 javascript 将日期传递给 vue 实例,但是在第一次使用 v-for 渲染列表后,当我使用其他日期调用该函数时,它会保留显示前一个数据。 这是我的功能:
function updateDate(fdate) {
var datefieldVal = document.getElementById('date').value;
var locationfieldVal = document.getElementById('location').value;
if (datefieldVal && locationfieldVal) {
var tslot = new Vue({
el: '#time-slots-container',
data: {
slot: {}
},
mounted: function () {
this.fetchTimeslot();
},
methods: {
fetchTimeslot: function () {
var that = this;
$.ajax({
type: "GET",
url: timeslotApiURL + "?date='" +fdate+ "'",
contentType: "application/json;",
dataType: "json",
success: function (data) {
that.slot = JSON.parse(data.d);
setTimeout(showTimeSlotAndButton, 500);
}
});
}
});
}
}
有人知道如何使用新的槽数据更新 v-for 列表吗?谢谢
最佳答案
假设您的数据正确返回,可能只是插槽
没有反应。尝试:
success: function (data) {
Vue.set(that.$data, 'slot', JSON.parse(data.d))
...
查看上面的代码,您应该避免每次想要更新日期时创建和安装新实例。我不确定 Vue 在这种情况下会做什么,但它可能会失败,因为您无法将另一个实例安装到现有实例。
而是将所有 Vue 代码移到 updateDate 函数之外。
然后,如果您需要阻止 v-for 在获得数据之前触发,只需添加一个 dateReady
数据参数,并在完成 ajax 请求后将其设置为 true,即
data: {
slot: {},
dateReady: false,
},
...
success: function (data) {
Vue.set(that.$data, 'slot', JSON.parse(data.d))
that.dateReady = true
...
然后您只需将 v-if="dateReady"
添加到您的 v-for
元素即可:
<div v-if="dateReady" class="time-slot-row" v-for="hourly in slot.TimeSlot">
如何将 fdate
传递给 ajax 请求现在的处理方式有所不同,但您可以有类似的内容:
var datefieldVal = document.getElementById('date').value;
var locationfieldVal = document.getElementById('location').value;
if (!datefieldVal || !locationfieldVal)
return
var tslot = new Vue({
el: '#time-slots-container',
data: {
slot: {},
dateReady: false,
},
mounted: function() {
this.fetchTimeslot();
},
methods: {
fetchTimeslot: function() {
var that = this;
$.ajax({
type: "GET",
url: timeslotApiURL + "?date='" + that.getDate() + "'",
contentType: "application/json;",
dataType: "json",
success: function(data) {
that.slot = JSON.parse(data.d);
that.dateReady = true
setTimeout(showTimeSlotAndButton, 500);
}
});
},
getDate () {
// whatever you do here
return ''
},
},
})
// wherever else you are using this...
tslot.fetchTimeslot()
本质上,您将更多的逻辑移至 Vue 的实例中,即 getDate()
如果这是不可能的,那么您可以设置一个参数来保存您想要获取的日期,在ajax 调用并创建一个新方法来更新它。有很多方法可以解决这个问题,但主要问题是确保只有一个 vue 实例绑定(bind)到该 #time-slots-container
元素
关于javascript - ajax更新数据时无法更新v-for列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40863523/