vue.js - 如何在 vuex 操作上使用 setTimeout?
问题描述
我想清空警报状态,以便不显示警报,我真的不知道如何在 addMovieToFavourites 或 removeMovieToFavourites 执行后 x 秒触发 removeAlert 操作,代码如下,谢谢。
警报.js
const state = {
alert: null
}
const mutations = {
SET_ALERT(state, alert) {
state.alert = alert
},
REMOVE_ALERT(state) {
state.alert = null
}
}
const actions = {
setAlert({ commit }, alert) {
commit('SET_ALERT', alert)
},
removeAlert({ commit }) {
commit('REMOVE_ALERT')
}
}
media.js 添加/删除触发警报消息
const actions = {
addMovieToFavourites({ commit, dispatch }, movie) {
commit('ADD_FAVOURITE', movie)
const alert = {
type: 'success',
message: 'Added to favourites!'
}
dispatch('alert/setAlert', alert, { root: true })
},
removeMovieFromFavourites({ commit, dispatch }, movie) {
commit('REMOVE_FAVOURITE', movie)
const alert = {
type: 'success',
message: 'Removed from favourites!'
}
dispatch('alert/setAlert', alert, { root: true })
},
}
警报.vue
<script>
import { mapActions, mapState } from 'vuex'
export default {
name: 'Alert',
data() {
return {
timeout: null
}
},
mounted() {
this.timeout = setTimeout(() => this.removeAlert(), 3000)
},
beforeDestroy() {
clearTimeout(this.timeout)
},
computed: {
alertTypeClass() {
return `alert-${this.alert.type}`
},
...mapState('alert', ['alert'])
},
methods: mapActions('alert', ['removeAlert'])
}
</script>
解决方案
添加它并将其从media
操作中删除:
addMovieToFavourites({ commit, dispatch }, movie) {
commit('ADD_FAVOURITE', movie)
const alert = {
type: 'success',
message: 'Added to favourites!'
}
// Add alert
dispatch('alert/setAlert', alert, { root: true })
// Remove alert
setTimeout(() => {
dispatch('alert/removeAlert', { root: true })
}, 3000)
}
如果所有警报都以这种方式工作,您可以通过在操作中排队来自动触发从每个警报中删除setAlert
:
const actions = {
setAlert({ commit }, alert) {
commit('SET_ALERT', alert);
setTimeout(() => {
commit('REMOVE_ALERT');
}, 3000);
},
...
}
那么你就不需要这个removeAlert
动作了。
您可能还需要一些警报管理或clearTimeout
在 3 秒内处理多个警报。正如它所写的那样,先前的警报的删除可能意味着以后的警报整整 3 秒都没有显示。
推荐阅读
- swift - 使用关系和谓词访问 Core Data 中的数据
- python - 如何循环单击按钮然后向下单击
- r - 数据框中是否可以有一系列数字?
- java - 如何让用户使用正则表达式 java 输入某种格式
- python - 对象不显示可用方法
- javascript - 反应内存泄漏 - 当通过传递给提供者的孩子的函数更新上下文提供者中的状态时
- powershell - 为什么“Get-PowerBIDataset”Powershell 命令会为我提供工作区中的所有数据集?
- python - python bytearray 到 C++ 对象
- unit-testing - 如何在具有特定结构的 golang 应用程序中运行测试并获得覆盖率?/
- java - Chrome 和 selenium 无头开关?