D
D
devilsD2018-12-13 20:29:57
Vue.js
devilsD, 2018-12-13 20:29:57

How to make an instance property in VUE reactive?

In the plugin, I declare the prototype property:
Vue.prototype.$dataGroups = [];
But as it turned out, it is not reactive.
Setting the property with Vue.set didn't work either:

Vue.set(Vue.prototype, '$dataGroups', ["navigation"]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2018-12-13
@bingo347

Hmm, something like this comes to mind:

const box = new Vue({data: {groups: []}});
Object.defineProperty(Vue.prototype, '$dataGroups', {
  configurable: true,
  get() { return box.groups; },
  set(value) { box.groups = value; }
});

PS You have different properties of $dataGroups and $dataGroupsActive
PSS having objects/arrays in the prototype is not a good practice, it's better to do it like Vuex throws $store into instances via mixin: https://github.com/vuejs/vuex/ blob/dev/src/mixin.js#L22
UPD : mixin example:
Vue.mixin({
  beforeCreate() {
    const {$options} = this;
    const {parent} = $options;
    if($options.dataGroups) {
      const groups = typeof $options.dataGroups === 'function' ? $options.dataGroups() : $options.dataGroups;
      const box = new Vue({data: {groups}});
      Object.defineProperty(this, '$dataGroups', {
        configurable: true,
        get() { return box.groups; },
        set(value) { box.groups = value; }
      });
      return;
    }
    if(!parent) { return; }
    const descriptor = Object.getOwnPropertyDescriptor(parent, '$dataGroups');
    if(!descriptor) { return; }
    Object.defineProperty(this, '$dataGroups', descriptor);
  }
});

A
Anton Anton, 2018-12-13
@Fragster

If you want something simple, then you can use a simple state container and use the event bus for the actor component model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question