我有一個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
。但是其中也有不少,而且有點混亂。
是否有更清潔的方法可以用來更好地實現這一目標?
我實際上沒有父組件。父母只是應用程序的根。但據推測,我可以使用根數據進行相同的連接?我試圖避免總是定義它,因爲它看起來沒有必要,因爲該組件僅在使用相同VueJS代碼的幾個其他頁面中的一個窗體上使用。 –
是的,同樣的概念適用,只需用你的應用程序的根目錄替換我的「父組件」,根就像任何其他的一樣是有效的父目錄。 –