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?