Vue.js VueJS-组件如何获取全局数据项?

Vue.js VueJS-组件如何获取全局数据项?,vue.js,Vue.js,我有这样的代码: Vue.component("sample", { inherit: true, template: "#sample", props: { active : "active", ... }, methods: { forceChangeActive: function(){ var activeItem = this.$parent._data.active;

我有这样的代码:

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);
        }
    }
});
新Vue中有活动和showModal数据变量。现在,如果我使用this.active或this.showmodel,这两个函数都没有定义。 控制台输出为:

  • 函数对象{active=0,showmodel=false}之前
  • 模式错误,activeItem 0
  • 模态真,激活项2
  • 函数对象{active=0,showmodel=false}之前

  • 如何在新Vue或组件中更改变量的值?

    inherit:true
    不推荐使用

    您需要使用属性将
    active
    showmodel
    显式传递给子组件。您可以使用
    .sync
    确保它们也共享回父级:

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