[英]watch not getting all in Vue
<template>
<v-form :model='agency'>
<v-layout row wrap>
<v-flex xs12 sm12 lg12 >
<v-layout row wrap>
<v-flex xs12 md12 class="add-col-padding-right">
<v-radio-group
v-model="agency.location"
:mandatory="true"
label="Please select one of the options below">
<v-radio label="NYC" value="nyc"></v-radio>
<v-radio label="SAN JOSE" value="san_jose"></v-radio>
</v-radio-group>
</v-flex>
</v-layout>
</v-flex>
</v-layout>
</v-form>
</template>
<script>
export default {
data: function () {
return {
agency: {
id: '',
name: '',
location: '',
contacts: {
name: '',
number: '',
address: ''
}
},
final_location_contact: {
name: '',
number: '',
address: ''
}
}
}
watch: {
agency: {
handler(val){
if (this.agency.location === "nyc") {
this.final_location_contact = this.agency.contacts;
}
}
},
created: function() {
this.fetchAgency();
},
method: {
fetchAgency() {
this.$axios.get('/agency.json')
.then(response => {
if (Object.keys(response.data).length > 0) {
this.agency = response.data;
}
}).
then(() => {
});
},
}
}
</script>
我在這里面臨的問題是頁面加載時,並且 fetchAgency 方法運行並且我能夠獲取代理數據。 當我從單選按鈕中選擇 select 時,我可以將值 agent.contacts 值分配給 final_location_contact。 但是當我首先 select San Jose 單選按鈕選項和之后我 select nyc 單選按鈕然后我無法將值 agent.contacts 值分配給 final_location_contact 時,我無法將值分配給 final_location_contact,因為我使用調試器檢查了 agent.contacts 的值是空的. 但如果我第一次使用 select nyc,它就不是空的。 任何想法可能是問題所在?
'agency.location': {
handler (newValue, oldValue) {
if (newValue === "nyc") {
this.final_location_contact = this.agency.contacts;
}
else {
this.final_location_contact.name: '',
this.final_location_contact.number: '',
this.final_location_contact.address: ''
}
}
}
您遇到的問題是,在 JavaScript 的眼中,當您更改agency
時,您並沒有更改agency.location
的值。 在語言agency
眼里還是一樣的object,不管你對它的屬性做什么。 那個觀察者正在等待對整個 object 進行更改,比如 agent agency = {different: "object"}
我建議你做的是將location
突破到它自己的頂級屬性並進行調整,如下所示:
data: function () {
return {
location: '',
agency: {
id: '',
name: '',
location: '',
contacts: {
name: '',
number: '',
address: ''
}
},
final_location_contact: {
name: '',
number: '',
address: ''
}
}
}
這樣,您可以像這樣在該屬性上設置一個觀察者:
watch: {
location: function(val) {
this.agency.location = val
if (val === "nyc") {
this.final_location_contact = this.agency.contacts;
}
}
},
正如雅各布所說,觀察者沒有被觸發,因為代理本身沒有改變。
在評論中我建議使用深度觀察者,但這不是最好的方法。 您可以通過以下方式專門收聽在“agency.location”上所做的更改:
watch: {
'agency.location': {
handler (newValue, oldValue) {
// this will be triggered every time `agency.location` is changed
}
}
}
這比深度觀看要好,看起來像這樣
watch: {
deep: true,
agency (newValue, oldValue) {
// logic
}
}
因為只要agency
或其任何屬性發生變化,就會觸發深度觀察者。
這是小提琴,它演示了差異及其實現方式(確保打開控制台)。
如果未觸發觀察程序是此處的問題,則無需更改 model / 模板。
watch: {
'agency.location': {
handler (newValue, oldValue) {
var new_location = {}
if (newValue === "nyc") {
new_location = this.agency.contacts;
}
else {
new_location = {
name: '',
number: '',
address: ''
}
}
this.final_location_contact = new_location;
}
}
}
這就是我讓它工作的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.