Vue2 using $set does not fix change detection caveat when using push() on object

人走茶凉 提交于 2019-12-12 04:18:23

问题


Following on from this issue: Strange issue with Vue2 child component object v-for list render

I have a function which loops through an array products, which takes certain values and adds them to an object called attributes. I need to use this.$set to update my attributes object to make sure that Vue can detect the update.

My functions look like this:

//// checks if the value exists in the object to avoid adding duplicates

        doesItExist: function(key, value) {
            for (let i = 0; i < this.attributes[key].length; i++) {
                if (this.attributes[key][i] == value) return true;
            }
            return false;
        },


//// if the value does not exist, then add it to the object

        pushIfNotExists: function(key, value) {
            if (!this.doesItExist(key, value)) {   // returns true/false
                this.$set(this.attributes[key], key, this.attributes[key].push(value));
            }
        },


//// main function looping through the original products array to extract attributes

        createAttributes: function() {
            for (let i = 0; i < this.products.length; i++) {
                for (let j = 0; j < this.products[i]['attributes_list'].length; j++) {
                    let attributeName = this.products[i]['attributes_list'][j]['attribute_name'];
                    if (!this.attributes[attributeName]) {
                        this.attributes[attributeName] = new Array();
                    };
                    this.pushIfNotExists(attributeName, this.products[i]['attributes_list'][j]['value']);
                }
            }
            console.log(this.attributes);  // outputs expected object
        },

The problem I have is that in my child component, the attribute data is still not being rendered, which means this must not be working correctly (even though my console log shows the data is there).

Any ideas?

Thanks

来源:https://stackoverflow.com/questions/47190211/vue2-using-set-does-not-fix-change-detection-caveat-when-using-push-on-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!