[Vuejs]-How to create pagination as child component that reusable in VueJS

0👍

UPDATED

After tinkering a bit, finally i can solve it.

Computed array should be keep on parent component, and add an object that store begin and end index for sliced on collection array. Which that object will changed based on child events using methods.

parent.vue

<template>
    <pagination v-model="pageIndex"
        v-on:paginationInit="paginationInit"
        collections="students">
    </pagination>
</template>

data () {
    return {
        students: [] // collection
        pageIndex: {}
    }
},
computed: {
    studentList () {
        return this.students.slice(pageIndex.begin, pageIndex.end)
    }
},
methods: {
    // This method emitted from child component
    paginationInit (pageIndex) {
        this.pageIndex.begin = pageIndex.begin
        this.pageIndex.end = pageIndex.end
    }
}

And then in child component, the computed logic moved on a method here that handle event from clicked pagination element.

child.vue

data () {
    return {
        pageIndex: { begin: 0, end: 10 }
    }
},
created () {
    this.init()
},
methods: {
    init () {
        this.$emit('paginationInit', this.pageIndex)
    },
    handleCurrentChange (page) {
        this.pageIndex.begin = (page - 1) * this.pageSize
        this.pageIndex.end = this.pageSize * page
        this.$emit('input', this.pageIndex)
    }
}

Leave a comment