During my Vue.js project, I attempted to create a global alert/notification system at the root level of the application. My approach involved pushing objects into an array and passing it to the component.
In my app.vue file:
<template>
<div id="app">
<alert-queue :alerts="$alerts"></alert-queue>
<router-view></router-view>
</div>
</template>
In my main.js file:
exports.install = function (Vue, options) {
Vue.prototype.$alerts = []
}
And here is my alert_queue.vue component:
<template>
<div id="alert-queue">
<div v-for="alert in alerts" >
<transition name="fade">
<div>
<div class="alert-card-close">
<span @click="dismissAlert(alert)"> × </span>
</div>
<div class="alert-card-message">
{{alert.message}}
</div>
</div>
</transition>
</div>
</div>
</template>
<script>
export default {
name: 'alert',
props: {
alerts: {
default: []
}
},
data () {
return {
}
},
methods: {
dismissAlert (alert) {
for (let i = 0; i < this.alerts.length; i++) {
if (this.alerts[i].message === alert.message) {
this.alerts.splice([i], 1)
}
}
}
}
}
</script>
I can successfully add items to the list using this.$alerts.push({})
and confirm their addition with console logs. However, the issue arises when the component fails to recognize these additions without a manual code change and webpack reload. Is there a way to programmatically trigger a refresh for prototype components within Vue.js?
I experimented with adding a $alerts object to the root file, but attempts to access it using $root.$alerts.push({})
were unsuccessful due to $root being read-only. Are there alternative approaches that could be taken to address this issue?