Vue - Использование плагина в качестве прототипа - PullRequest
0 голосов
/ 19 февраля 2019

Я использую euvl / vue-messages для уведомлений в моем приложении.Каждый раз, когда я хочу уведомить пользователя, мне нужно написать следующий код:

Если внутри компонента Vue:

this.$notify({
    group: 'panel',
    type: 'success',
    duration: 5000,
    text: 'message'
})

Или если внутри файла .js:

Vue.notify({
    group: 'panel',
    type: 'success',
    duration: 5000,
    text: `message`
})

Я хочу создать файл поддержки, аналогичный шине событий , и просто позвонить в следующую строку, чтобы написать уведомление:

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

1 Ответ

0 голосов
/ 19 февраля 2019

Я думаю, вы почти достигли того, что хотите, кроме использования Object.defineProperty.Попробуйте вернуть function ссылку вместо Vue.notify метода get.

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