Vue - 使用插件作为原型
Vue - Using plugin as prototype
我正在使用 euvl/vue-notification 接收有关我的应用程序的通知。每次我想通知用户我需要写下面的代码:
如果在 Vue 组件内:
this.$notify({
group: 'panel',
type: 'success',
duration: 5000,
text: 'message'
})
或者如果在 .js 文件中:
Vue.notify({
group: 'panel',
type: 'success',
duration: 5000,
text: `message`
})
我想创建一个类似于 event bus 的支持文件,只需调用以下行来编写通知:
this.$notify('message')
这是我迄今为止尝试过但没有成功的方法...
main.js
import Vue from 'vue'
import App from './App.vue'
import notifications from './support/notifications'
Vue.use(notifications)
new Vue({
render: h => h(App)
}).$mount('#app')
notifications.js
import Vue from 'vue'
import Notifications from 'vue-notification'
Vue.use(Notifications)
export default function install(Vue) {
Object.defineProperty(Vue.prototype, '$notify', {
get(message) {
return Vue.notify({
group: 'panel',
type: 'success',
duration: 5000,
text: message
})
}
})
}
我认为你几乎实现了你想要的,除了使用 Object.defineProperty
。
在 get
方法上尝试 return function
引用而不是 Vue.notify
的 return。
import Vue from 'vue'
import Notifications from 'vue-notification'
Vue.use(Notifications)
export default function install(Vue) {
Object.defineProperty(Vue, 'notification', {
get() {
return notification;
}
})
Object.defineProperty(Vue.prototype, '$notification', {
get() {
return notification;
}
})
}
function notification(message) {
Vue.notify({
group: 'panel',
type: 'success',
duration: 5000,
text: message
})
}
我正在使用 euvl/vue-notification 接收有关我的应用程序的通知。每次我想通知用户我需要写下面的代码:
如果在 Vue 组件内:
this.$notify({
group: 'panel',
type: 'success',
duration: 5000,
text: 'message'
})
或者如果在 .js 文件中:
Vue.notify({
group: 'panel',
type: 'success',
duration: 5000,
text: `message`
})
我想创建一个类似于 event bus 的支持文件,只需调用以下行来编写通知:
this.$notify('message')
这是我迄今为止尝试过但没有成功的方法...
main.js
import Vue from 'vue'
import App from './App.vue'
import notifications from './support/notifications'
Vue.use(notifications)
new Vue({
render: h => h(App)
}).$mount('#app')
notifications.js
import Vue from 'vue'
import Notifications from 'vue-notification'
Vue.use(Notifications)
export default function install(Vue) {
Object.defineProperty(Vue.prototype, '$notify', {
get(message) {
return Vue.notify({
group: 'panel',
type: 'success',
duration: 5000,
text: message
})
}
})
}
我认为你几乎实现了你想要的,除了使用 Object.defineProperty
。
在 get
方法上尝试 return function
引用而不是 Vue.notify
的 return。
import Vue from 'vue'
import Notifications from 'vue-notification'
Vue.use(Notifications)
export default function install(Vue) {
Object.defineProperty(Vue, 'notification', {
get() {
return notification;
}
})
Object.defineProperty(Vue.prototype, '$notification', {
get() {
return notification;
}
})
}
function notification(message) {
Vue.notify({
group: 'panel',
type: 'success',
duration: 5000,
text: message
})
}