简体   繁体   English

在Vue.JS中观看动态嵌套数据?

[英]Watching dynamic nested data in Vue.JS?

I have a series of checkboxes setup in Vue.js components that are emitting data to my parent element. 我在Vue.js组件中设置了一系列复选框,这些复选框向我的父元素发射数据。 I want to watch this data for changes and append the data within the object to an API call, in order to filter data. 我想观察此数据的变化并将该对象内的数据附加到API调用中,以便过滤数据。

Here's what my data on the parent element looks like when some items are checked (otherwise it's just an empty object if nothing's checked): 这是检查某些项目时我在父元素上的数据的样子(否则,如果未进行任何检查,它只是一个空对象):

selectedFeatures对象的图像

I want to be able to insert this data into an API call that would (in general) look like this, when the data changes: 我希望能够在数据更改时将这些数据插入(通常)如下所示的API调用中:

this.axios.get('http://localhost:8000/api/v1/schools' + 
    for (feature in selectedFeatures) {
        '?features[]=' + feature
    }
).then((response) => {
    this.$root.$emit('searchQuery', response.data);
});

Usually this is pretty easy with the Watch feature of Vue, but since my data is nested in unnamed arrays and generated dynamically, I'm not sure how to do this. 通常,借助Vue的Watch功能,这非常容易,但是由于我的数据嵌套在未命名的数组中并动态生成,因此我不确定如何执行此操作。

Fixed by adding the following to Filters.vue's tags: 通过在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));
}

I then changed the Checkbox.vue slightly by replacing: 然后,我通过替换来稍微更改了Checkbox.vue:

<input type="checkbox" :disabled="disabled" :name="name" v-model="newValue" @change="$emit('change', newValue, $event)">

to: 至:

<input type="checkbox" :disabled="disabled" :name="name" v-model="newValue" @change="valueChanged">

and added: 并添加:

methods: {
    valueChanged() {
        this.$root.$emit('checkUpdated');
        this.$emit('change', this.newValue, this.$event);
    }
}

Which the mounted lifecycle can catch on the Filters.vue file to fire the method. 装入的生命周期可以捕获到Filters.vue文件中的哪一个来触发该方法。

Works great! 很棒!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM