Моя проблема заключается в отображении значений объекта. В таблице указаны задачи и оставшееся время до их выполнения. Но не обновляет таймер обратного отсчета... Значения находятся в объекте в идентификаторе задачи, например: Объект {1: "4017 D 13 H 2 M 49 S", 2: "0 D 0 H 0 M 0 S", ...} Этот объект должен всегда обновляться, чтобы показывать оставшееся время, но в таблице, где я показываю объект, то же самое только с первым значением, без обновления таймера.
<template>
...
<table class = "table" style = "text-align: center">
<thead>
<tr>
<th scope = "col">...</th>
<th scope = "col">...</th>
<th scope = "col">...</th>
<th scope = "col">...</th>
<th scope = "col">Time Left</th>
</tr>
</thead>
<tbody>
<tr class = "table-warning" v-for = "task in tasks" :key = "task.id">
<th scope = "row">{{task.id}}</th>
<th>{{task.description}}</th>
<th>{{task.created_at}}</th>
<th>{{task.redline}}</th>
<th>{{showLeft[task.id]}}</th>
</tbody>
</table>
...
</template>
<script>
export default {
// variables declaration
data() {
return {
user: [],
tasks: [],
numTasks: "",
currentTime: [],
showLeft: {}
};
},
created() {
// ProgressBar animation starts
this.$Progress.start();
// Get data from server
axios.get("/user/name/data").then(response => {
this.user = response.data;
axios.get(`/user/missingTaskNum/data`).then(response => {
this.numTasks = response.data;
axios.get(`/user/missingTask/data`).then(response => {
this.tasks = response.data;
// Call function that will calculate time left
this.updateCurrentTime();
// ProgressBar animation stops
this.$Progress.finish();
});
});
});
},
mounted() {
// start timer to refresh function every 1 sec
this.interval = setInterval(() => {
this.updateCurrentTime();
}, 1000);
},
methods: {
updateCurrentTime: function() {
var now = new Date().getTime();
for (let i = 0; i < this.tasks.length; i++) {
this.currentTime[this.tasks[i].id] = new Date(this.tasks[i].redline) - now;
if (this.currentTime[this.tasks[i].id] < 0) {
this.$Progress.start();
this.$Progress.finish();
console.info("EXPIROU ID: " + this.tasks[i].id);
} else {
var days = Math.floor(
this.currentTime[this.tasks[i].id] / (1000 * 60 * 60 * 24)
);
var hours = Math.floor(
(this.currentTime[this.tasks[i].id] % (1000 * 60 * 60 * 24)) /
(1000 * 60 * 60)
);
var minutes = Math.floor(
(this.currentTime[this.tasks[i].id] % (1000 * 60 * 60)) /
(1000 * 60)
);
var seconds = Math.floor(
(this.currentTime[this.tasks[i].id] % (1000 * 60)) / 1000
);
this.showLeft[this.tasks[i].id] =
days + " D " + hours + " H " + minutes + " M " + seconds + " S ";
}
}
console.info(this.showLeft);
}
},
beforeDestroy() {
clearInterval(this.interval);
}
};
</script>
Простите за это..






Вы столкнулись с одним из предупреждений об обнаружении изменений, описанным здесь:
https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Предостережения
Конкретно в этой строке:
this.showLeft[this.tasks[i].id] =
days + " D " + hours + " H " + minutes + " M " + seconds + " S ";
Объект this.showLeft пуст, когда он создается внутри data, поэтому у него не будет никаких реактивных свойств. Он отлично работает, если вы измените его на это:
this.$set(
this.showLeft,
this.tasks[i].id,
days + " D " + hours + " H " + minutes + " M " + seconds + " S "
)
Это говорит Vue добавить реактивное свойство к showLeft, чтобы пользовательский интерфейс обновлялся при его изменении.
Альтернативой может быть создание нового объекта каждый раз:
// Somewhere near the top of updateCurrentTime
const showLeft = {};
// ... set values on showLeft instead of this.showLeft
this.showLeft = showLeft
Лично я думаю, что лучше бы использовал для этого вычисляемые свойства, а не пытался делать все внутри updateCurrentTime. Я не могу быть более конкретным, учитывая, что код неполный.
Спасибо, работает работает отлично! А за подсказку попробую реализовать этот метод!
Пожалуйста, включите код в вопрос, вместо того, чтобы пытаться обмануть систему, чтобы она разрешила вам ссылаться на совместное использование кодов, добавив текст там, где должен быть код.