Unattended vuejs prototype arrays are not being monitored

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)"> &times; </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?

Answer №1

To create a more efficient communication system within your Vue application, consider turning $alerts into a Vue instance and using it as an event bus:

exports.launch = function (Vue, options) {
  Vue.prototype.$alerts = new Vue({
    data: {alerts: []},
    events: { ... },
    methods: { ... }
  })
}

This setup allows you to easily add alerts by calling this.$alerts.addAlert() in your components, which then adds the alert to the array and triggers the alert-added event. You can also listen for this event in other places using

this.$alerts.on('alert-added', (alert) => { ... }

If you're looking for a more powerful solution, consider integrating Vuex, a state management library specifically designed for situations like this: https://github.com/vuejs/vuex

Answer №2

When properties are defined on Vue.prototype, they do not react the same way as data properties on a Vue instance.

In my opinion, using Jeff's method or employing Vuex is usually the best approach.


One alternative method is to assign this.$alerts as a data property of a Vue instance, making it reactive and allowing changes to reflect in the global $alerts array:

Vue.prototype.$alerts = ['Alert #1'];

Vue.component('child', {
  template: `<div><div v-for="i in items">{{ i }}</div></div>`,
  props: ['items'],
})

new Vue({
  el: '#app',
  data() {
    return {
      globalAlerts: this.$alerts,
    }
  },
  methods: {
    addToArray() {
      this.globalAlerts.push('Alert #' + (this.globalAlerts.length + 1));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.min.js"></script>
<div id="app">
  <child :items="$alerts"></child>
  <button @click="addToArray">Add alert</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Escaping quotes in JavaScript

After receiving a JSON object in the following format: result: { image: "..." title: "text text \"text\"" } I am currently utilizing underscore.js to render the template, but I am encountering an issue where the title displays with the escape ...

Creating an empty array within an object in JavaScript

Consider the following scenario: var form = { header: { value: null, isValid: false, type: 'textinput', rules: { isRequired: true, ...

problems encountered when trying to deploy a backend api on the Render platform

Encountered this error: May 14, 04:27:30 PM - Error [email protected]: The "node" engine is not compatible with this module. Expected version ">=14.20.1". Received version "14.17.0". May 14, 04:27:30 PM - Incompatible module detected. Verified my ...

Generating elevation graph from a kml file with the combination of php and javascript

Currently, I am exploring the Google Elevation Service with the goal of creating an elevation profile similar to the one showcased in this example: Below is the JavaScript code snippet used: var elevator; var map; var chart; var infowindow = new google.m ...

Is there a way to conceal the toggle division following a postback in ASP.NET?

Here is the script code I am working with: <script type="text/javascript> $(document).ready(function () { var $content = $(".contentPersonalDetail").hide(); $(".togglePersonalDetail").on("click", function (e) { $(this ...

Tips for building a MongoDB document that includes both objects and arrays, along with the corresponding schema in Mongoose

Need assistance with saving data in a mongodb database such as the following: { name: "Just a name", questions: [ { question: "Question 1", answerOptions: [ {id: 0, text: "answer 1"}, ...

Steps for inserting telephone numbers from a database into an <a href="tel:"> tag

<a href="tel:<?php echo $b2b_mec_num; ?>"><button type="button" class="btn" id="CallBtn">&nbsp;CALL</button></a> I am looking to dynamically add phone numbers from a database to the anchor tag provided in the code snippet ...

Why is it that when I use XMLHttpRequest for a menu and request a page with HTML that contains JavaScript, nothing happens?

Below is the code snippet I'm using for a menu in a webpage I am currently developing. In some cases, the page I want to request contains JavaScript, but when the requested page is loaded into the actual page, the script does not run. //Ajax menu all ...

Error Found in Angular2 Console Inspection

So, when I check the webpage inspection console, I see this error: Uncaught SyntaxError: Unexpected token { at Object.<anonymous> (main.bundle.js:3885) at __webpack_require__ (polyfills.bundle.js:51) at eval (eval at <anonymous> (m ...

Ways to exchange information among Vue components?

My role does not involve JavaScript development; instead, I focus on connecting the APIs I've created to front-end code written in Vue.js by a third party. Currently, I am struggling to determine the hierarchy between parent and child elements when ac ...

What are the steps to implement IndexedDB in an Angular application?

I'm searching for a solution to utilize indexedDB within Angular. I need assistance with implementing data recovery or potentially using a browser-based database that doesn't have the 5 MB limit like localStorage. Can anyone point me in the right ...

Can the axios version be displayed during runtime?

I have incorporated axios into my project using npm import axios from 'axios' Is there a way to print the version of axios in the console after the entire application has been compiled? ...

Algorithm using JavaScript to identify objects within an array

I am working with an array of objects that contain information about different projects. Each project has a unique ID and two arrays, one containing the IDs of projects that will happen before it, and another with the IDs of projects that will follow. Here ...

Unable to retrieve parameter while making a POST request

Need some help with attribute routing. I'm having trouble getting parameters from the HTTP body. The ConnectionID Class includes a property named CValue. $('#btn').click(function () { $.ajax({ type: "POST", url: "http:// ...

I encountered an error stating that ".then" is not defined during my attempt to save

Just starting out with node.js and I encountered an issue: TypeError: Cannot read property 'then' of undefined This is the code snippet causing the problem: router.post("/signup", (req, res) => { const userRegister = new UserRegister({ ...

Error: The function this.form._updateTreeValidity does not exist

Currently utilizing Angular Forms version 2.0.0, I am in the process of creating a contact us modal that contains a contact form. Upon loading the ContactComponent, an exception is thrown: EXCEPTION: this.form._updateTreeValidity is not a function htt ...

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

What is the best way to trigger dependent APIs when a button is clicked in a React Query application

On button click, I need to call 2 APIs where the second query depends on the result of the first query. I want to pass data from the first query to the second query and believe using "react-query" will reduce code and provide necessary states like "isFetch ...

Cordova's Dynamic Scrolling Feature for iOS Overflowing Elements

When using the Safari iOS browser, listening to scroll events triggers the console message every time, even during momentum. However, in the Cordova built app, the message is only triggered when the scroll has stopped. el-with-webkit-overflow-scrolling-to ...