我似乎无法弄清楚如何自动关闭我的警报。我将警报存储在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>
答案 0 :(得分:0)
以下是一种可能的解决方案:
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>