首页 > 解决方案 > Vuejs 通知插件

问题描述

我正在编写第一次使用基本 javascript(无 ES)的 vuejs 插件。

代码如下:

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

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);
            }
        }
    });
}
}

问题是当我写入控制台以下命令时:

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

我得到错误:

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

如果我运行 chrome 调试器,我可以看到对象是可访问的。在 Vue.mixins data() return 命令上将错误打印到控制台。

我看不出有什么问题,我错过了什么?

标签: javascriptvue.jspluginsvuejs2

解决方案


尝试这个:

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

反而:

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

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

我试图回复您的代码工作,如果在return {}返回后不使用断线,则不起作用。


推荐阅读