0
votes

I am passing in products as a prop to this component. I am then setting a data value to those props because I am going to be pushing products to it.
In my template, I am using a computed property productsToShow because if a prop hideSoldOutProducts is passed in, they get filtered out.

My question is: I made productsData a data value because at the bottom of the page, their will be an API call to push more products to the productsData array. So although the productsData is being added to, the computed property productsToShow() which is using the productsData is not reflecting this.

<template>
    <div v-for="(product, index) in productsToShow">
      .....
    </div>
</template>

data() {
    return {
        productsData:       Vue.util.extend([], this.products.data)
    }
},
props: {
    products:            {type: Object},
    hideSoldOutProducts: {type: Boolean}
},
computed: {
    productsToShow() {
        if (!this.products.data) {
            return []
        }

        if (this.hideSoldOutProducts) {
            let filteredList = this.productsData.filter(x => x.product.inventory_quantity.quantity > 1)
            return filteredList
        } else {
            return this.productsData
        }
    }
}
1
How are you adding products to productsData?Steven B.
I this.productsData = response.data.data in the success part of the API call so I can see this.productsData having more data added to it in the Vue devtoolsherkypam

1 Answers

0
votes

It feels like there might be a better approach, since this looks quite complex. But perhaps the reactivity is not working because the data is only set on mount. You could set a watcher on your property and bind the new property data to productsData on a change.

But, I have the feeling that it might be a better approach to create an addProduct methods that will push a product into you data array. Something like this.

watcher: {
    products(value) {
        value.data.forEach(this.addProduct);
    }
},
methods: {
    addProduct(product) {
       // here you could also check if the product already exists in your 
       // productsData
       this.productsData.unshift(product);
    },
    fetchProducts() {
        this.$http.get('/api/products')
                  .then(resp => {
                      // Now we can loop through and add the products.
                      resp.data.forEach(this.addProduct);
                  });
    }
}

I hope this helps.