gpt4 book ai didi

javascript - 在 Vue.JS 中观察动态嵌套数据?

转载 作者:行者123 更新时间:2023-12-01 03:35:50 25 4
gpt4 key购买 nike

我在 Vue.js 组件中设置了一系列复选框,这些复选框将数据发送到我的父元素。我想观察这些数据的变化,并将对象内的数据附加到 API 调用,以便过滤数据。

这是检查某些项目时父元素上的数据的样子(否则,如果未检查任何内容,它只是一个空对象):

image of selectedFeatures object

我希望能够将此数据插入到 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 文件来触发该方法。

效果很好!

关于javascript - 在 Vue.JS 中观察动态嵌套数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com