Reinis Grinvalds
Reinis Grinvalds

Reputation: 45

VueJS - how component gets global data item?

I have code like this :

Vue.component("sample", {
    inherit: true,
    template: "#sample",
    props: {
       active : "active",
       ...
    },
    methods: {
      forceChangeActive: function(){
         var activeItem = this.$parent._data.active;
         var modalSetup = this.$parent._data.showModal;
         console.log("1.before function", this.$parent._data);
         this.$parent.$options.methods.baseAction(activeItem, modalSetup);
         console.log("2.before function", this.$parent._data);
      });
    }
});
new Vue({
    el: "#app",
    data: {
        active: 0,
        showModal: false,
        ...
    }, 
    methods: {
        baseAction: function(activeItem, modalSetup){
            console.log("3.modal", modalSetup, "activeItem": activeItem);
            modalSetup = true;
            activeItem = 2;
            console.log("4.modal", modalSetup, "activeItem": activeItem);
        }
    }
});

There are active and showModal data variables in new Vue. Now I'm getting undefined for both if I use this.active or this.showModal. And console output is:

  1. before function Object { active=0, showModal=false }
  2. modal false, activeItem 0
  3. modal true, activeItem 2
  4. before function Object { active=0, showModal=false }

How I can change variable`s values in new Vue or in component?

Upvotes: 1

Views: 1247

Answers (1)

Jeff
Jeff

Reputation: 25221

inherit:true is deprecated.

You need to explicitly pass active and showModal to the child component using properties. You can use .sync to make sure they are shared back to the parent as well:

<sample :active.sync="active" :show-modal.sync="showModal"></sample>

Upvotes: 2

Related Questions