[英]Watching dynamic nested data in Vue.JS?
我在Vue.js組件中設置了一系列復選框,這些復選框向我的父元素發射數據。 我想觀察此數據的變化並將該對象內的數據附加到API調用中,以便過濾數據。
這是檢查某些項目時我在父元素上的數據的樣子(否則,如果未進行任何檢查,它只是一個空對象):
我希望能夠在數據更改時將這些數據插入(通常)如下所示的API調用中:
this.axios.get('http://localhost:8000/api/v1/schools' +
for (feature in selectedFeatures) {
'?features[]=' + feature
}
).then((response) => {
this.$root.$emit('searchQuery', response.data);
});
通常,借助Vue的Watch功能,這非常容易,但是由於我的數據嵌套在未命名的數組中並動態生成,因此我不確定如何執行此操作。
通過在Filters.vue的標簽中添加以下內容進行修復:
methods: {
addFeatures() {
var featureNames = '';
// Loop through selectedFeatures and return a string of all features
for (var key in this.selectedFeatures) {
var obj = this.selectedFeatures[key];
for (var prop in obj) {
// Remove spaces and add + sign
featureNames += '&features[]=' + obj[prop].split(' ').join('+');
}
};
return 'http://localhost:8000/api/v1/schools?' + this.selectedGrade + '=1' + featureNames;
}
},
mounted() {
// When checkUpdated is emited, run new API call
this.$root.$on('checkUpdated', function() {
var gradeFeatures = this.addFeatures();
// Dump string from addFeatures into end of API and send it to the root to filter out data
this.axios.get( gradeFeatures ).then((response) => {
this.$root.$emit('searchQuery', response.data);
});
}.bind(this));
}
然后,我通過替換來稍微更改了Checkbox.vue:
<input type="checkbox" :disabled="disabled" :name="name" v-model="newValue" @change="$emit('change', newValue, $event)">
至:
<input type="checkbox" :disabled="disabled" :name="name" v-model="newValue" @change="valueChanged">
並添加:
methods: {
valueChanged() {
this.$root.$emit('checkUpdated');
this.$emit('change', this.newValue, this.$event);
}
}
裝入的生命周期可以捕獲到Filters.vue文件中的哪一個來觸發該方法。
很棒!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.