javascript - 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 命令上将错误打印到控制台。
我看不出有什么问题,我错过了什么?
解决方案
尝试这个:
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 {}
返回后不使用断线,则不起作用。
推荐阅读
- javascript - Heroku 应用程序崩溃状态 503。可能会出现哪些问题?
- docker - 从 jenkins 访问 kubernetes docker for desktop
- r - 警告:因子包含隐含的 NA
- dataset - 用 Scapy 合成数据包
- java - 无法在 feign builder 中引发期望
- php - 在 PHP 中从 SFTP 获取最新文件(使用 CURL)
- salt-stack - 状态应用期间的 Saltstack 发送事件
- c - 将地址或指针传递给 C 函数
- facebook - Facebook - 如何从 Instant Games 中删除加载屏幕
- php - 如何在我的服务中使用学说方法(Symfony 4)?