Countdown variable (HH:mm:ss) - vue.js

I parse a date YYYY-mm-dd and calculate the difference till midnight. The result will be always under 24h, for example 10:01:10 - HH:mm:ss till it expires. I wonder how I could achieve a countdown functionality with the given example.
<template>
<Label :text="date.expires | readableTime"></Label>
</template>
filters: {
readableTime(value) {
var now = moment(new Date());
var end = moment(value);
var diff = moment.duration(end.diff(now));
try {
return moment.utc(diff.as("milliseconds")).format("HH:mm:ss");
} catch (e) {
return "00:00:00";
}
}
}

You must use use timer and reactive data property. I recommend you to safe diff to components data, start timer on component mount and clear it beforeDestroy
data() {
return {
diff: this.calculareDiff()
}
}
methods: {
calculareDiff() {
const now = moment(new Date());
const end = moment(this.date.expires);
this.diff = moment.duration(end.diff(now));
}
},
mounted() {
this.timer = setInterval(() => this.calculareDiff(), 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}

Related

How to pass a computed as a prop to a component?

I have 1 component to which I pass a computed as a prop in this way:
<Datatable :extraParams="extraParams" />
the computed is in the attached image.
I'm having trouble with the value of this property: coverageSelected:coverageData
Coverage data is filled by a select multiple
The problem I have is that when selecting an element of the select, first the component function is executed, then the coverageSelected property is empty, then the computed is executed and until this moment the coverageSelected array is filled, then until the second attempt It already has a full array.
This is my computed
props: [
"status_selected",
"rows",
"totals",
"dateRangeValue",
"coverageSelected",
"coverageList",
"showAll",
"dateFilterSelected",
],
computed(){
extraParams() {
let coverageData = this.coverageList.filter((m) => this.coverageSelected.includes(m.variable));
return {
status: this.status_selected,
dateRange: this.dateRangeValue,
dateFilterSelected: this.dateFilterSelected,
coverageSelected: coverageData, //This is the property that is not late.
showAll: this.showAll,
};
},
}
Another detail to mention that this.coverageSelected is a prop
The method that is executed first in the computed is this:
async getList(params) {
this.loading = true;
try {
if (params) {
this.query = { ...this.query, ...params, ...this.extraParams, filters: this.filters };
} else {
this.query = { ...this.query, ...this.extraParams, filters: this.filters };
}
const { data } = await this.$axios.post(`${this.$config.routePrefix}${this.action}`, this.query);
if (data.code == 200) {
this.rows = data.rows;
this.total = data.total;
this.$emit("listed", data);
}
} finally {
this.loading = false;
}
},

realtime clock with vue js

I've written a small clock component for one of my projects,
but I didn't get the value for my clock refreshed.
A short extract of my code:
time() {
let now = new Date();
let hour = this.zeroPadding(now.getHours());
let minute = this.zeroPadding(now.getMinutes());
let second = this.zeroPadding(now.getSeconds());
console.log(hour.toString() + minute.toString() + second.toString())
if(!this.realtime)
return this.value
else
return hour.toString() + ":" + minute.toString() + ":" + second.toString()
}
},
mounted() {
setInterval(() => {
this.time()
}, 1000)
},
beforeDestroy () {
clearInterval(this.polling)
}
Does anyone finde the mistake?
Did I understand the polling wrong?
Greetings,
Matthias
The time value that you want to display needs to be a data / computed property so that it's reactive and Vue can track it. Concise way to do it:
export default {
data() {
return {
interval: null,
time: null
}
},
beforeDestroy() {
// prevent memory leak
clearInterval(this.interval)
},
created() {
// update the time every second
this.interval = setInterval(() => {
// Concise way to format time according to system locale.
// In my case this returns "3:48:00 am"
this.time = Intl.DateTimeFormat(navigator.language, {
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
}).format()
}, 1000)
}
}

is it possible to access variable in watch() function vue

I want to access variable asd in my watch() function and clear asd interval I tried code below but it's not working timer goes below 0 so any possible solutions?
methods:{
testing(){
this.sTimer--;
if(this.sTimer == 0){
clearInterval(this.asd)
}
}
},
watch(){
var asd = setInterval(() => this.testing(), 1000);
}
Your watcher is not watching any thing! You need to provide an data item for which it watches for it's changes
watch: {
item: function (newItem, oldItem) {
console.log(oldItem + " changed to: " + newItem);
}
},
Also, you might want to add your asd variable to data section.
data() {
return{
asd = null;
}
},
methods: {
testing(){
this.sTimer--;
if(this.sTimer == 0){
clearInterval(this.asd)
}
}
},
watch() {
item: function (newItem, oldItem) {
this.asd = setInterval(() => this.testing(), 1000);
}
}

Wait until API fully loads before running next function -- async/await -- will this work?

I am a beginner with Javascript with a bit of knowledge of VueJs. I have an array called tickets. I also have a data api returning two different data objects (tickets and user profiles).
The tickets have user ids and the user profiles has the ids with names.
I needed to create a method that looks at both of that data, loops through it, and assigns the full name of the user to the view.
I was having an issue where my tickets object were not finished loading and it was sometimes causing an error like firstname is undefined. So, i thought I'd try and write an async/await approach to wait until the tickets have fully loaded.
Although my code works, it just doesn't "feel right" and I am not sure how reliable it will be once the application gets larger.
Can I get another set of eyes as to confirmation that my current approach is OK? Thanks!
data() {
return {
isBusy: true,
tickets: [],
userProfiles: [],
}
},
created() {
this.getUserProfiles()
this.getTickets()
},
methods: {
getUserProfiles: function() {
ApiService.getUserProfiles().then(response => {
this.userProfiles = response.data
})
},
getTickets() {
ApiService.getTickets().then(response => {
this.tickets = response.data
this.assignNames(this.tickets)
this.isBusy = false
})
},
// lets wait until the issues are loaded before showing names;
async assignNames() {
let tickets = await this.tickets
var i
for (i = 0; i < this.tickets.length; i++) {
if (tickets[i].assigned_to !== null) {
const result = this.userProfiles.filter(profile => {
return profile.uid == tickets[i].assigned_to
})
tickets[i].assigned_to = result[0].firstname + ' ' + result[0].lastname
}
}
}
}
}
</script>
There are several ways you could do this. Here is the one I prefer without async/await:
created() {
this.load();
},
methods: {
getUserProfiles: function() {
return ApiService.getUserProfiles().then(response => {
this.userProfiles = response.data
})
},
getTickets() {
return ApiService.getTickets().then(response => {
this.tickets = response.data
})
},
load() {
Promise.all([
this.getUserProfiles(),
this.getTickets()
]).then(data => {
this.assignNames();
this.isBusy = false;
});
},
assignNames(){
const tickets = this.tickets;
for (let i = 0; i < this.tickets.length; i++) {
if (tickets[i].assigned_to !== null) {
const result = this.userProfiles.filter(profile => {
return profile.uid == tickets[i].assigned_to
})
tickets[i].assigned_to = result[0].firstname + ' ' + result[0].lastname
}
}
}
}

VueJS: setInterval method not working properly

Please tell me what am i doing wrong? I want to active 'cloth' update every 2 sec. Still learning vue. Thanks
data() {
return {
clothes: ['t-shirts', 'sneakers', 'jackets'],
count: 0,
cloth: ''
}
},
methods: {
startInterval() {
setInterval(() => {
this.cloth = this.clothes[this.count]
this.count++
if (this.count >= this.clothes.length) {
this.count = 0;
}
}, 2000)
}
}
Vue has a life cycle that you can leverage to complete this objective. You can hook into the created function and execute your interval within:
created() {
this.startInterval()
},
This is not a method. It will be a sibling to your data and method properties.