如何在 vuex 动作上使用 setTimeout?

How to use setTimeout on vuex action?

我想清空警报状态,以便不显示警报,我真的不知道如何在执行 addMovieToFavourites 或 removeMovieToFavourites 后 x 秒触发 removeAlert 操作,代码如下,谢谢。

alert.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 })
  },
}

alert.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 秒。