首页 > 解决方案 > 数据更改时vue原型没有反应

问题描述

我尝试创建一个自定义插件来存储数据以将其用作全局。这是我的自定义插件

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

当我尝试从我的 vue 模板运行 $pushNotifs 方法以将一些数据推送到 $notif.notifications 时,模板不会更新(但它的值在那里)

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

如何使其对模板产生反应?

标签: javascriptvue.jsvuejs2vue-component

解决方案


我遵循了这个答案。基本上,您创建一个类并使用一个新的 Vue 实例来提供响应性。

插件.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;

然后使用它(在 main.js 中):

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

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

并访问它:

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

在模板中:

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

因此,您可以在此处state访问所有数据,或者您可以像我在此处显示的那样公开单个项目。


推荐阅读