2016-04-28 74 views
1

我有一個VueJS地址查找組件。從VueJS組件共享數據

Vue.component('address-lookup', 
{ 
    template: '#address-lookup-template', 
    data: function() 
    { 
     return { 
      address: {'name': '', 'town:': '', 'postcode': ''}, 
      errors: {'name': false, 'town': false, 'postcode': false}, 
      states: {'busy': false, 'found': false}, 
      result: {} 
     } 
    }, 
    methods: 
    { 
     findAddress: function(event) 
     { 
      if(typeof event === 'object' && typeof event.target === 'object') 
      { 
       event.target.blur(); 
      } 

      $.ajax(
      { 
       context: this, 
       url: '/lookup', 
       data: 
       { 
        'name':  this.address.name, 
        'town':  this.address.town, 
        'postcode': this.address.postcode 
       }, 
       success: function(data) 
       { 
        this.states.busy = false; 
        this.states.found = true; 
        this.address.name = data.name; 
        this.result = data; 
       } 
      }); 
     }, 
     reset: function() 
     { 
      this.states.found = false; 
      this.result = {}; 
     } 
    } 
}); 

裏面我的模板,我那麼勢必結果像這樣:

<p>{{ result.formatted_address }}</p> 

有結果內返回(如Twitter的手柄)一些額外的數據,是不是地址的一部分查找模板,併發生在窗體的單獨部分。由於與我的表單結構有關的原因,我不能在同一個模板中包含這些輸入。

我發現了一種方法來綁定這些輸入,雖然它感覺有點'哈克'。

<input type="text" name="twitter" v-model="$refs.lookupResult._data.result.twitter"> 

這一切工作正常。

我的問題是,表單被包含作爲一個更大的模板的一部分,有時在創建新記錄的上下文中,有時在編輯的上下文中。編輯記錄時,查找組件被刪除(使用if服務器端,所以模板不再被加載),當發生這種情況時,我得到這個錯誤。

$refs.lookupResult._data.result.twitter": TypeError: Cannot read property '_data' of undefined 

這是有道理的。 lookupResult定義,當我包括模板,編輯,當我刪除此行:

<address-lookup v-ref:lookup-result></address-lookup> 

我已經包括版本每個額外的輸入沒有v-model屬性,再次使用服務器端圍繞它的工作if。但是其中也有不少,而且有點混亂。

是否有更清潔的方法可以用來更好地實現這一目標?

回答

1

所以我不知道你的佈局的層次結構,它沒有在上面指出,但假設地址查找組件是你的父項的子項,並且實際上你需要在該父項中查找地址的結果如:

<parent-component> <!-- where you need the data --> 
    <address-lookup></address-lookup> <!-- where you lookup the data --> 
</parent-component> 

那麼你可以簡單地傳遞數據的道具,無論是自上而下的唯一(默認)或雙向定義「地址」例如在你父母的VUE數據鉤:

// parent's data() function 
data = function() { 
    return { 
    address: {} 
    } 
} 

// parent template, passed address with .sync modifier (to make it bi-directional) 
<parent-component> 
    <address-lookup :address.sync='address'></address-lookup> 
</parent-component> 

// have the props accepted in the address look up component 
var addressComponent = Vue.extend({ 
    props: ['address'] 
}) 

現在在你的$ .ajax成功函數中,只需在上設置你需要的道具。當然,你可以用你需要的所有道具來做到這一點:錯誤,結果,狀態等等。更好的是,如果你可以將它們嵌套在父對象上的一個鍵上,你可以傳遞包含所有四個元素的對象的單個鍵在所有四個分開。

+0

我實際上沒有父組件。父母只是應用程序的根。但據推測,我可以使用根數據進行相同的連接?我試圖避免總是定義它,因爲它看起來沒有必要,因爲該組件僅在使用相同VueJS代碼的幾個其他頁面中的一個窗體上使用。 –

+0

是的,同樣的概念適用,只需用你的應用程序的根目錄替換我的「父組件」,根就像任何其他的一樣是有效的父目錄。 –