3
votes

I have a json response from an laravel api with 800 items on it. I wish to show 15 items to the user. The user ll have to click 'Load More' button to show more 15.

Everything is working as expected but Vue Js throws this warning :

[Vue warn]: Error in render: "TypeError: Cannot read property 'slice' of undefined"

Code:

<div class="col" v-for="value in products.products.slice( 0, productsShow)">
//logic {{value.content}}
</div>
<button 
v-if="products.products.length > 15 && 
productsShow < products.products.length" 
@click="loadMore">
Load more products
</button>

VueJs

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                products: [],
                productsShow: ''
            }
        },
        methods: {
            loadMore () {
                this.productsShow += 15
            }
        },

        created() {
            axios.get('/api/products/pt').then(response => this.products = response.data)
            this.productsShow = 15
        }
    }
</script>

Also Tried this :

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                products: [],
                productsShow: 15
            }
        },
        methods: {
            loadMore () {
                this.productsShow += 15
            }
        },

        created() {
            axios.get('/api/products/pt').then(response => this.products = response.data)
        }
    }
</script>

Edit Api response : Api Laravel Response

2
Your products is an array not an object, so you can not do products.products.Alicia
Do you mean to use products.slice( 0, productsShow) instead of products.products.slice( 0, productsShow)?Terry
THe page is working exactly and rendering as I want. But I get that warning. This is the data : i.stack.imgur.com/WUqmR.jpg. -> products.slice( 0, productsShow) -> Doesnot workbmpf_pt
Its a object of arraysbmpf_pt

2 Answers

3
votes

It's because you are instantiating products as an array, when it's intended to be an object with the property 'products'. So you should change your data declarations to look like this.

 export default {
    data() {
        return {
            products: {
                products: []
            },
            productsShow: 15
        }
    }
}

also in your template, you can do this as well.

<div
    class="col"
    v-if="products.products"
    v-for="value in products.products.slice( 0, productsShow)"
>

Either one will work.

0
votes

Check if you are returning a json object and not a php one meaning does your api endpoint has something like this return response()->json($response);