javascript - 在突变处理程序之外改变 vuex 存储状态
问题描述
我创建了一个自定义计时器组件,但我收到了关于 vuex 存储的错误。该组件在创建并放入存储时启动一个计时器,然后每分钟增加一次时间。如果该人离开页面,就像计时器在商店中一样,则保存时间,当该人返回该页面时,计时器将自行恢复。
这是我的组件
<template>
<div>
<v-icon v-if="timer.visibility" :color="timeColor" @click="changeTimer">
{{ $icons.clock }}
</v-icon>
</div>
</template>
<script>
export default {
props: {
value: {
type: Number,
required: true
},
id: {
type: Number,
default: null
},
type: {
type: String,
default: null
}
},
data() {
return {
timer: {
actif: false,
visibility: false,
timeOut: null,
dateDebut: null,
id: 0
}
}
},
computed: {
listeTimer() {
return this.$store.state.listeTimerPointage
},
timeColor() {
return this.timer.actif ? 'green' : 'red'
},
count: {
get() {
return this.value
},
set(val) {
this.$emit('input', val)
}
}
},
beforeDestroy() {
this.stopTimer()
},
created() {
let precedentTimer = null
if (this.id > 0) {
if (this.listeTimer.length > 0) {
precedentTimer = this.listeTimer.filter((f) => f.id === this.id)
}
} else {
this.timer.id = 0
}
this.startTimer(precedentTimer)
},
methods: {
// Start le timer
startTimer(precedentTimer) {
if (precedentTimer !== null) {
this.timer = precedentTimer
this.count = precedentTimer.count
} else {
this.count = 1
this.timer.dateDebut = new Date()
if (this.timer.timeOut === null) {
this.timer.actif = true
this.timer.visibility = true
this.timer.timeOut = setTimeout(() => {
this.timerBoucle()
}, 60000)
}
}
// this.listeTimer.push(this.timer)
this.$store.commit('addListeTimerPointage', this.timer)
},
// Arrete le timer
stopTimer() {
this.timer.actif = false
clearTimeout(this.timer.timeOut)
},
// Met en place la boucle toute les 1 minutes
timerBoucle() {
const now = new Date()
const diff = now - this.timer.dateDebut
this.count += Math.round(diff / 60000)
this.timer.dateDebut = new Date()
this.timer.timeOut = setTimeout(() => {
this.timerBoucle()
}, 60000)
},
// Modifie l'état du timer
changeTimer() {
this.timer.actif = !this.timer.actif
if (!this.timer.actif) {
clearTimeout(this.timer.timeOut)
} else {
this.timer.dateDebut = new Date()
this.timer.timeOut = setTimeout(() => {
this.timerBoucle()
}, 60000)
}
}
}
}
</script>
我确实改变了一个状态,但我不认为我直接改变了状态
这是商店:
addListeTimerPointage(state, data) {
state.listeTimerPointage.push(data)
},
deleteTimer(state, data) {
const newArray = state.listeTimerPointage.filter(
(item) => item.id !== data
)
state.listeTimerPointage = newArray
}
谢谢你的帮助
解决方案
推荐阅读
- sed - 用 sed 将多行文本中的一个匹配模式替换为另一个
- django - 为什么在 Django 模板中列出索引它不在输出中?
- reactjs - 如何在同一个 const 函数中使用道具和导航路线(反应原生)?
- php - 无需从 Android 端调用 POST 或 GET 请求即可将更新从 PHP Web 应用程序发送到 Android 应用程序
- python-3.x - Pandas column:按特定顺序排列的列列表
- swift - SwiftUI 按字体大小偏移 Text()
- java - 如何将回车符附加到字符串?
- python - 有没有办法在运行时为模型的相关字段动态选择一个值?
- google-bigquery - 根据 bigquery 表中的列计算年龄
- html - 如何在图标和文本之间留出一个小空间