Vuejs announcement component

This is my first time developing a Vue.js plugin using basic JavaScript (not ES).

Here is the code snippet:

var NotificationStore =
{
state: [], // notifications will be stored here

removeNotification(timestamp)
{
    const indexToDelete = this.state.findIndex(n => n.timestamp === timestamp);

    if (indexToDelete !== -1)
        this.state.splice(indexToDelete, 1);
},
addNotification(notification)
{
    notification.timestamp = new Date();
    notification.timestamp.setMilliseconds(notification.timestamp.getMilliseconds() + this.state.length);

    this.state.push(notification);
},
notify(notification)
{
    if (Array.isArray(notification))
    {
        notification.forEach((notificationInstance) =>
        {
            this.addNotification(notificationInstance);
        });
    }
    else
        this.addNotification(notification);
}
}

var NotificationPlugin =
{
install(Vue, options)
{
    Vue.mixin(
    {
        data: function ()
        {
            var data =
                {
                    notificationStore: NotificationStore
                };

            return data;
        },
        methods:
        {
            notify(notification)
            {
                this.notificationStore.notify(notification);
            }
        }
    });

    Object.defineProperty(Vue.prototype, "$notify",
    {
        get() { return this.$root.notify }
    });

    Object.defineProperty(Vue.prototype, "$notifications",
    {
        get() { return this.$root.notificationStore }
    });

    Vue.component("notifications",
    {
        data()
        {
            return { notifications: this.$notifications.state };
        },
        methods:
        {
            removeNotification (timestamp)
            {
                this.$notifications.removeNotification(timestamp);
            }
        }
    });
}
}

When I try to run the command in console:

app.$notify({message:"Hello",type:"success",icon:"",horizontalAlign:"right",verticalAlign:"bottom"});

I encounter an error message:

vue.js:597 [Vue warn]: Error in data(): "TypeError: Cannot read property 'notificationStore' of undefined"

Although the object seems accessible when inspecting through Chrome debugger. The error occurs during the execution of Vue.mixins data() return statement.

I'm unable to identify any issues, what could I be overlooking?

Answer №1

give this a shot:

Vue.mixin(
    {
        data: function ()
        {
            return {
                    notificationStore: NotificationStore
            };
        },
        methods:
        {
            notify(notification)
            {
                this.notificationStore.notify(notification);
            }
        }
    });

alternatively:

Vue.mixin(
    {
        data: function ()
        {
            var data =
                {
                    notificationStore: NotificationStore
                };

            return data;
        },
        methods:
        {
            notify(notification)
            {
                this.notificationStore.notify(notification);
            }
        }
    });

I attempted to debug your code and found that if you do not include return {} without a line break after return, then it won't work properly.

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

Editing static blocks directly within the content area

My website consists of pages with title and content blocks. I am looking to incorporate a feature that allows users to edit content inline. This means they should be able to click on the title text or content block and edit it right then and there. Can an ...

"Is there a way to loop through elements in JavaScript similar to how you

When working in bash, I typically use the following code: for i in {0..2}; do echo x$i; done However, when attempting to replicate this function in JavaScript with the following code: for (var i=0; i<3; i++) { console.log(x$i); }; It is evident t ...

Unlocking Top-Level Accordion in Bootstrap 5 Nested Accordion by using Links to Open Nested Accordions

I am currently working on a page that involves nested accordions in Bootstrap 5. The concept is to have a button that triggers a nested accordion within another accordion, but I'm facing issues with making it function as intended. Although the button ...

Javascript continues to conceal my web background without my permission

After loading my webpage, I click on a link and the expected javascript runs as planned. However, once it completes and presents the results, the page goes blank to a white screen displaying only the outcomes. My goal is to have these results showcased o ...

Error: Unable to locate module '@/components/Header' in Next.js project

I'm currently facing an issue while working on my Next.js project. The problem arises when I attempt to import a component into my 'page.js' file. In the 'src' folder, I have a subdirectory named 'components' which contai ...

Why are the links in the navgoco slide menu failing to function properly?

I utilized a demo from jQueryRain to create a collapsible menu using jQuery. However, after completion, I discovered that none of the links were functioning properly. Upon visiting the documentation page, I noticed that many users were encountering the sam ...

Implement isotope filter on product page details using ASP.NET Core MVC

While working on my .Net core project, I implemented an isotope filter dynamically. Everything seemed to be functioning correctly, however, a minor error occurred. When selecting a specific category, the position of the product did not appear as expected. ...

Experience the power of module federation in Next JS without using the @module-federation/nextjs-mf package

Currently transitioning from Java to JavaScript, I am working on a Next.js project. I have a requirement to share the client component from this Next.js project with another project built on React. Upon discovering module federation, I successfully created ...

Transforming JavaScript controls into jQuery

I have been working on implementing touch controls for a JavaScript game, and I came across a solution that seemed promising. It involved using jQuery, but I needed to convert it to pure JavaScript to make it compatible with my game. The original code in ...

Error in React UseTable: Attempting to read properties of an undefined object (specifically trying to use a forEach loop)

https://i.stack.imgur.com/ZSLSN.pngHaving an issue here that I need some quick help with! Whenever I attempt to render data into a React table, I encounter the error mentioned above. The data is fetched from an API using Axios. Let's take a look at t ...

Extract JSON Data from Nested Object

I'm currently struggling with parsing JSON data from an object within an object using a Node.js script. Here's the JSON Object: { "Item":{ "job_change_request":"task0020764", "id":"a156fc4e-e8d4-424f-a792-0c8cf8e3ca46", ...

Issue with Vue filters not being resolved if the file is located outside of the project root

When I attempt to import a filters file from outside of the project directory using import Vue; Vue.filter(...), I encounter the error message Failed to resolve filter. If I duplicate the file and place it within the app's folder, the filter function ...

The module '../xcode' could not be located. This issue is occurring within React Native and Expo CLI, where the required stack cannot

Trying my hand at creating my first project using React Native in iOS with expo.io, I encountered an error when running the command "expo start": https://ibb.co/f2xsmpN https://i.sstatic.net/Uyxkk.png Despite attempts to reinstall and update Xcode, usin ...

Learn how to efficiently manage XHR requests one after the other in ExtJS 4.1 without relying on synchronous requests

My software relies on a sophisticated database structure with numerous foreign key constraints, leading to multiple callback handlers in my JavaScript code. One simple action like creating a new order might require three XHRs to submit all the required dat ...

How can I animate SVG paths to fade in and out sequentially?

My current code is causing the path to fade in/out all at once instead of one after the other var periodClass = jQuery(this).parent().attr("class"); jQuery("svg path").each(function(i) { var elem = jQuery(this); if (elem.hasClass(periodClass)) ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Filtering a 2-dimensional array based on a specific string match

I have an array with various objects and I am trying to find all objects that have the string "en-GB". However, I am encountering an issue with my current approach that gives me the error message "Cannot use 'in' operator to search for 'en&a ...

Enhancing jQuery functionality by inserting two elements after instead of just one

I'm currently facing an issue with the insertion of a span element using the insertAfter method when selecting another ID to hide other elements. The problem arises when I select an ID for the first time, as it inserts a span element. However, when I ...

Every time I attempt to access the Instagram API through Axios, I consistently encounter the dreaded "CORS policy blocking" issue

Currently, I am attempting to retrieve images from my Instagram account within a Laravel application that utilizes Vue on the front end. Surprisingly, this process works flawlessly in a standalone Vue application. However, when integrating it with Laravel, ...

Tips for managing unfinished transactions through Stripe

I have successfully set up a checkout session with Stripe and included a cancel_url as per the documentation. However, I am facing an issue where the cancel_url is only triggered when the user clicks the back button provided by Stripe. What I want to achie ...