我正在创建一个组件来显示应在 Vue 中几秒钟后自动关闭的通知,我的警报组件发出一个“过期”事件,然后我在父级中侦听此事件,并使用拼接将其从父级数据数组中删除,这有时有效,但有时不会删除“警报”。
Vue.component('alert', {
template: '<li><slot></slot></li>',
mounted() {
setTimeout(() => this.$emit('expired'), 2000)
}
});
new Vue({
el: '#app',
data: {
count: 0,
alerts: []
},
methods: {
createAlert(){
this.alerts.push(this.count++)
},
removeItem(index) {
this.alerts.splice(index, 1)
}
}
});
Run Code Online (Sandbox Code Playgroud)
看到这个 Fiddle并点击Create Alert按钮几次,一些警报不会被解除。关于如何解决这个问题的任何想法?
如评论中所述,不要按索引执行此操作。这是一种选择。
<div id="app">
<button @click="createAlert">
Create Alert
</button>
<alert v-for="(alert, index) in alerts" :key="alert.id" :alert="alert" @expired="removeItem(alert)">{{ alert.id }}</alert>
</div>
Vue.component('alert', {
props: ["alert"],
template: '<li><slot></slot></li>',
mounted() {
setTimeout(() => this.$emit('expired', alert), 2000)
}
});
new Vue({
el: '#app',
data: {
count: 0,
alerts: []
},
methods: {
createAlert(){
this.alerts.push({id: this.count++})
},
removeItem(alert) {
this.alerts.splice(this.alerts.indexOf(alert), 1)
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1789 次 |
| 最近记录: |