Vue.js通知插件

时间:2018-08-01 11:47:58

标签: javascript vue.js plugins vuejs2

我正在使用基本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()返回命令上将错误打印到控制台。

我看不到任何问题,我想念什么?

1 个答案:

答案 0 :(得分:0)

尝试:

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 {}而没有换行符结尾的行,则无法正常工作。