gpt4 book ai didi

javascript - Vue - 使用插件作为原型(prototype)

转载 作者:行者123 更新时间:2023-12-01 01:15:57 26 4
gpt4 key购买 nike

我正在使用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之外,您几乎已经实现了您想要的目标。尝试返回 function 引用,而不是 Vue.notifyget 方法上的返回。

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

关于javascript - Vue - 使用插件作为原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54770115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com