cahyowhy
cahyowhy

Reputation: 563

vue prototype not reactive when data changes

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?

Upvotes: 4

Views: 3250

Answers (1)

ierdna
ierdna

Reputation: 6293

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.

Upvotes: 4

Related Questions