2016-03-23 33 views
1

我有這樣的代碼:VueJS - 組件如何獲取全局數據項?

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.showModal未定義。 和控制檯輸出是:

  1. 之前功能對象{活性= 0,的ShowModal = FALSE}
  2. 模態假,activeItem 0
  3. 模態爲真,activeItem 2
  4. 之前功能對象{活性= 0,showModal = false}

如何在新的Vue或組件中更改變量的值NT?

回答

2

inherit:true已棄用。

您需要使用屬性明確地將activeshowModal傳遞給子組件。您可以使用.sync以確保將它們共享回父級:

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