1

我似乎无法弄清楚如何自动关闭我的警报。我将警报存储在 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>
4

1 回答 1

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>
于 2016-05-13T17:00:00.733 回答