Хранилище:
state: {
date: null,
interval: null,
},
mutations: {
update(state) {
state.date = new Date();
},
start(state) {
if (!state.interval) {
state.interval = setInterval(this.commit, 1000, 'update');
}
},
stop(state) {
if (state.interval) {
clearInterval(state.interval);
state.interval = null;
}
},
},
Компонент:
computed: {
timerActive() {
return !!this.$store.state.interval;
},
timeStr() {
const { date } = this.$store.state;
return date instanceof Date
? [ 'getHours', 'getMinutes', 'getSeconds' ]
.map(n => `${date[n]()}`.padStart(2, 0))
.join(':')
: 'ВРЕМЕНИ НЕТ';
},
},
created() {
this.$store.commit('start');
},
<button @click="$store.commit('start')" :disabled="timerActive">start</button>
<button @click="$store.commit('stop')" :disabled="!timerActive">stop</button>
<div>{{ timeStr }}</div>