vue.js - 如何在 vuex Action 上使用 setTimeout?

标签 vue.js vuejs2 vuex settimeout vuex-modules

我想清空警报状态,以便不显示警报,我真的不知道如何在 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')
  }
}

媒体.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 秒内都不会显示。

关于vue.js - 如何在 vuex Action 上使用 setTimeout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61153703/

相关文章:

vue.js - Vue CLI 3 使用 Terser 删除 console.log 和代码注释

unit-testing - axios 捕获错误请求失败,状态码为 404

javascript - 将 vuex 状态和突变绑定(bind)到基于 TypeScript 的 Vue 中的复选框组件属性

javascript - 在应用程序加载之前将数据加载到 vuex 存储中,如何完成?

javascript - 如果不在模板中使用特定的 vuex 状态,单击处理程序将无法工作

typescript - 将 mapState 与 typescript 一起使用

javascript - 如何在 Bootstrap 选项卡中创建多个 Vue 组件?

vue.js - Vue组件动态添加属性

javascript - 使用面板标题左侧的图标验证扩展面板

vue.js - Vue过滤器和 "Do not mutate vuex store state outside mutation handlers"