2016-05-13 46 views
1

我似乎無法弄清楚如何自動解僱我的提醒。我將這些警報存儲在Vuex中,並且我正在通過操作創建警報。可以有任何數量的警報,並且應該按照創建它們的順序來解除它們。爲了便於說明,我正在創建一些警報,每700毫秒一次。我希望提醒在設定的時間後按照創建順序自動解除。我不知道如何做到這一點,或者是否有更好的方法來處理不屬於Vuex的全局警報消息。這裏是我的代碼:Vue.js自動關閉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

這裏是一個可能的解決方案:

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

基本上,你創建一個自定義指令:

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

,您可以添加到V的,有回調作爲參數

<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>