4

I try to create a custom plugin to store data to use it as global. this is my custom plugin

    import {remove} from 'lodash'

    export const notifications = {
      install(Vue, options = {}) {
        Vue.prototype.$notifs = {
          count: 0,
          notifications: []
        }

        Vue.prototype.$pushNotifs = ({content, type, timeout}) => {
          Vue.prototype.$notifs.count++
          Vue.prototype.$notifs.notifications.push({content, type, timeout, id: Vue.prototype.$notifs.count})
        }

        Vue.prototype.$removeNotifs = ({id}) => {
          Vue.prototype.$notifs.notifications = remove(Vue.prototype.$notifs.notifications, (item) => item.id !== id)
        }

        Vue.mixin({
          computed: {
            $notifications() {
              return this.$notifs.notifications
            }
          }
        })
      }
    }

when i try to run $pushNotifs methods from my vue template to push some data to $notif.notifications, the template won't updated (but the value its there)

...
methods: {
      pushNotifs() {
        this.$pushNotifs({content: 'contoh content', type: 'success', timeout: 500})
        console.log(this.$notifs.notifications); // has the value
      }
    }
....

how to make it reactive to the template?

3
  • do you have a computed property in your component when you retrieve the notification like return this.$notifs.notifications??? Commented May 1, 2018 at 6:11
  • i dont have it. can you make an example hehe @roliroli Commented May 1, 2018 at 6:58
  • it is something funny? Commented May 1, 2018 at 6:59

1 Answer 1

4

I followed this answer. Basically, you create a class and use a new Vue instance to provide reactivity.

plugin.js:

import Vue from 'vue';
class Notif {
    constructor() {
        this.VM = new Vue({ 
            data: () => ({
                notifs: [],
                count: 0,
            }),
        });
    }
    get state() {
        return this.VM.$data;
    }

    get count() {
        return this.VM.$data.count;
    }
}

const notif = {
    Store: Notif,
    install (Vue, options) {
        Vue.mixin({
            beforeCreate() {
                this.$notif = options.store;
            }
        });
    },

};
export default waiter;

then to use it (in main.js):

import notif from './plugins/plugin.js';

Vue.use(notif, {
    store: new notif.Store()
});

and access it:

this.$notif.state.notifs.push('some notif');

in the template:

<span>{{$notif.count}}</span>

so here state gives you access to all the data, or you can expose individual items as i've shown here.

Sign up to request clarification or add additional context in comments.

Comments

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.