Vue Plugin's array does not exhibit reactivity

My application has a simple plugin that handles communication between components. There is a specialized component called "Communicates.vue" which listens for changes in an array declared in the plugin and displays toast messages. However, I am facing an issue with reactivity as the array always remains empty. I'm certain that I have implemented something similar before and it worked fine. Can you spot what I might have missed?

Communicates.vue

    <div class="communicates">
        {{$communicates.messages}} <!-- always empty :( -->
        <transition-group mode="fade" name="toasts">
            <Toast
                v-for="communicate in $communicates.messages"
                :key="communicate"
                :communicate="communicate"
                @close="$communicates.remove(communicate)"
            />
        </transition-group>
    </div>
</template>
<script>
import Toast from '@/components/Toast';
import { mapGetters, mapActions } from 'vuex';

export default {
    components: {
        Toast
    }
}
</script>

Plugin:

const Communicates = {
    install(Vue) {
        Vue.prototype.$communicates = {
            messages: [],
            success(message) {
                this.messages.push({ type: 'success', message })
                debugger; // OK, app stops here, so it should be added
            },
            error(message) {
                this.messages.push({ type: 'error', message })
            },
            remove(communicate) {
                this.messages.splice(this.messages.indexOf(communicate), 1)
            }
        }
    }
}

export default Communicates // of course I did Vue.use in main.js

Answer №1

Your $communicates object may not be reactive as expected. Consider making it reactive with the following code:

Vue.prototype.$communicates = Vue.observable({
  conversations: [],
  // add more properties here
})

Answer №2

Would you consider implementing fresh references?

Vue.prototype.$interact = {
  notes: [],
  achievement(note) {
    this.notes = this.notes.concat([{ type: 'achievement', note }])
  },
  failure(note) {
    this.notes = this.notes.concat([{ type: 'failure', note }])
  },
  delete(communication) {
    this.notes = this.notes.filter(note => note !== communication)
  }
}

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

Go through a website's JSON data and save necessary information into a document

My task is to extract data from website.json using the request module, then filter through this information and only save a specific value in a key:value format such as "thatvalue":thisvalue. This process needs to be done for all the available data. Sampl ...

Is there a mechanism in Vuefity that triggers an event when the number of items per page is switched? :switch-items-per-page-trigger

My tables have been customized with the following settings: :items-per-page="itemsPerPage" :footer-props="{ 'items-per-page-options': [10, 20, 30, 40, 50, -1] }" The itemsPerPage values are sourced from the user's pr ...

Default cursor for Internet Explorer: automatic

I have a container div that holds all of my website's content. I want this container to change the cursor to a pointer when clicked on, but I don't want the elements inside the container to inherit this cursor style: https://i.sstatic.net/8joJo. ...

When JSON data is copied and displayed in Node.js or JavaScript, it appears as a string

I have written a code to copy one JSON file into another JSON file. Here is the code: function userData(){ fs.copyFile( path.join(process.cwd(), "user/access.json"), path.join(process.cwd(), "client/access.json"), ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Ways to convert field data to lowercase in MongoDB query result

I have two Objects in my database collection. [ {"_id" : 1, name: "notLowercased"}, {"_id" : 2, name: "lowercased"}, ] Using find and $regex to search for names that include a specific string. data = await Catal ...

A step-by-step guide on using props to pass an image path and load it in

How can I use the imported image path in the component props to load it into an img tag src? Any assistance is appreciated. import amy from "./amy.jpg"; <AvatarProfileIcon icon="amy" /> <img src={props.icon} /> https://co ...

Is it possible to invoke a PHP function from within JavaScript?

Check out my JavaScript code: <script> $(document).ready(function(){ $(".five").click(function(){ <?php echo updatepoints();?> }); }); </script> Now take a look at my PHP code: <?php function updatepoints() { mysql_connect("localhos ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

What is the best way to detect and handle the destroy event in Kendo UI grids when a click event

How can I trigger a function when the delete button in a grid is clicked using JavaScript? ...

Merge two arrays of objects containing Google Map coordinates

I am facing a challenge with merging two object arrays that have similar values. var Cars = [{ lat: 42, lng: -72 }, { lat: 40.7127837, lng: -74.0059413 }, { lat: 40.735657, lng: -74.1723667 }]; var Trucks = [{ lat: 43, lng ...

Update the value of a JSF managed bean property for a h:SelectOneMenu using JavaScript

Hello, I have a unique method of injecting HTML code at runtime into my web page using JavaScript. The specific piece of code that I am cloning and inserting is as follows: <div id="any"> <h:selectOneMenu value="#{browserOSList.browserXP[0]}" ...

Vue Js error message: The following dependency could not be found: * core-js/fn/promise

While working on my Vuejs App, I encountered an error related to promises: I received the following error message: "This dependency was not found: core-js/fn/promise in ./src/store/index.js. To resolve this, you can run: npm install --save core-js/fn/promi ...

ReactJS: The function .useSelector() is not defined

I've been following a tutorial for a while and hit a roadblock trying to understand this. Both metaphorically and literally. On the Dashboard page, I attempted to use useSelector() to access the state of the goalSlice component. This component is ver ...

Adding a namespace in a .js file

In the MVC application I'm developing, all JavaScript for the pages is stored in separate JavaScript files without any script tags on the pages. There's a Messages class containing Errors, Information, and Confirmation classes with static strings ...

Endless loop within useEffect causing app to experience performance degradation

I am currently working on retrieving Routes based on a list from firebase realtime db. Below is the code I have: import { onValue, ref } from "firebase/database"; import React, { useEffect, useState } from "react"; import { Route, Route ...

Non-sticky hamburger menu is not fixed in place

Having trouble with the hamburger menu staying sticky? The hamburger icon remains in the corner as you scroll down, but the menu stays fixed at the top of the page, making it hard to access. You tried tweaking the code you found on Codepen, but couldn&apos ...

Assistance required: Click on the button to select and copy all text within the specified paragraph ID

Hey there! I've got a div with a dropdown menu that reveals text and images based on the selected option. What I want to achieve is having a button that allows users to copy all the content inside the div. Below is my sample code for the div dropdown ...

Expecting expression and a syntax error occurred: JSX nextjs token was unexpected

When rendering a table from an array, I utilized the following code: const Posts: NextPage = ({ posts}: any) => { return ( <> ..... <tbody> { posts.map((post: any) => { const _date = new ...

Unlocking ajax components using django

Currently, I am utilizing AJAX to retrieve Django model data and display the results. In my views.py file: def browse_jobs(request): keyword = request.GET.get('keyword', None) company = Company.objects.filter(title__icontains=keyword) ...