【问题标题】:Vue.js auto dismiss alert from Vuex storeVue.js 自动关闭来自 Vuex 商店的警报
【发布时间】:2016-09-09 21:44:00
【问题描述】:

我似乎不知道如何自动关闭我的警报。我将警报存储在 Vuex 中,并通过操作创建警报。可能有任意数量的警报,它们应该按照它们创建的顺序被解除。出于说明目的,我创建了许多警报,每 700 毫秒一个。我希望警报在设定的时间后按照它们的创建顺序自动关闭。我不确定如何执行此操作,或者是否有更好的方法来处理不属于 Vuex 的全局警报消息。这是我的代码:

https://jsfiddle.net/thL4rLta/1/

/*------ Animations ------*/
Vue.transition('fade', {
  enterClass: 'fadeInDown',
  leaveClass: 'fadeOutUp'
})

/* ----- Store ----- */
const state = {
  items: []
};

const mutations = {
  SHOW_ALERT (state, data) {
    data.id = Date.now()
    state.items.push(data)
  },
  HIDE_ALERT (state, item) {
     state.items.$remove(item)
  },
};

const store = new Vuex.Store({
  state,
  mutations
});

/* ----- Component ----- */
new Vue({
  el: '#app',
  store,
  vuex: {
    getters: {
      alerts: (state) => state.items
    },
    actions: {
      hideAlert: ({ dispatch }, alert) => dispatch('HIDE_ALERT', alert)
    },
  },
  methods: {
    dismiss (e) {
      this.hideAlert(e)
    }
  }
});

// Creat alerts
function doSetTimeout (i) {
  setTimeout(() => {
    store.dispatch('SHOW_ALERT', {message: 'sdfsdf'})
  }, 700 * i)
}

for (var i = 0; i <= 4; ++i) {
  doSetTimeout(i)
}

模板:

<div class='test' id="app">
  <div v-for="alert in alerts" 
      class="animated alert alert-dismissible alert-danger" 
      transition="fade" 
      v-bind:class="alert.type" 
      role="alert">
      <button @click="dismiss(alert)"type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span>
      </button>
    {{alert.message}}
  </div>
</div>

【问题讨论】:

    标签: twitter-bootstrap vue.js vuex


    【解决方案1】:

    这是一种可能的解决方案:

    https://jsfiddle.net/thL4rLta/2/

    基本上,您创建一个自定义指令:

    Vue.directive('delay', {
      params: ['cb'],
      bind: function () {
        setTimeout(this.params.cb, 3000)
      }
    })
    

    你可以添加到 v-for 中,使用回调作为参数

    <div class='test' id="app">
      <div v-for="alert in alerts" v-delay :cb="()=>{dismiss(alert)}"  
          class="animated alert alert-dismissible alert-danger" 
          transition="fade" 
          v-bind:class="alert.type" 
          role="alert">
          <button @click="dismiss(alert)"type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span>
          </button>
        {{alert.message}}
      </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 2023-04-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2014-12-12
      相关资源
      最近更新 更多