0

I'm using euvl/vue-notification for notifications on my application. Every time I want to notify the user I need to write the following code:

If inside a Vue component:

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

Or if inside a .js file:

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

I want to create a support file, similar to event bus and just call the following line to write a notification:

this.$notify('message')

This is what I tried until now but without success...

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 Answer 1

1

I think you almost achieved what do you want, except of using Object.defineProperty. Try to return a function reference instead of Vue.notify's return on get method.

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
    })
}
Sign up to request clarification or add additional context in comments.

9 Comments

E quem diria que uma simples função causaria esse problema hehe
Pois é. E quem diria que meu inglês esta tão ruim assim que os brasileiros já reconhecem,. huehueuhe
There is just one problem, inside .js files when I call: Vue.notify('message', 'error') nothing happens
Probabily the Maximum call stack size exceeded error is caused by a circular call. I changed the custom plugin to '$notification' to avoid name conflicts. Could you test it?
Worked... One more thing for life, do not use the same names as the plugin uses...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.