Skip to content

Instantly share code, notes, and snippets.

@Alexisgt01
Last active November 21, 2019 14:47
Show Gist options
  • Save Alexisgt01/d54935d2c4313922708544b025b979fd to your computer and use it in GitHub Desktop.
Save Alexisgt01/d54935d2c4313922708544b025b979fd to your computer and use it in GitHub Desktop.
Vuex multi timer methods
/* eslint-disable no-console */
/* eslint-disable no-unused-vars */
const state = {
timers: [],
};
// getters
const getters = {
timers: state => state.timers,
timer: (state) => (id) => {
return state.timers.find(el => el.id === id);
}
};
// actions
const actions = {
newTimer: ({commit}, id) => {
commit('ADD_TIMER', id);
},
toggleTime: ({commit}, id) => {
commit('TOGGLE_TIME', id);
},
stopTime: ({commit}, id) => {
commit('STOP_TIME', id);
},
};
// mutations
const mutations = {
ADD_TIMER: (state, id) => {
let today = new Date();
state.timers.push({
id: id,
time: 0,
isStoped: false,
isRunning: false,
timeStart: today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds(),
timeEnd: null,
interval: null,
});
},
TOGGLE_TIME: (state, id) => {
let time = state.timers.find(el => el.id === id);
let today = new Date();
time.timeEnd = null;
if (time.isRunning) {
clearInterval(time.interval);
} else {
time.interval = setInterval(() => {
++time.time
}, 1000)
}
if (time.isStoped) {
time.timeStart = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds()
time.isStoped = false;
}
time.isRunning = !time.isRunning
},
STOP_TIME: (state, id) => {
let today = new Date();
let time = state.timers.find(el => el.id === id);
clearInterval(time.interval);
time.isRunning = false;
time.isStoped = true;
time.time = 0;
time.timeEnd = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
time.timeStart = null;
time.interval = null;
},
};
export default {
namespaced: true,
strict: false,
state,
getters,
actions,
mutations
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment