Jamie
Jamie

Reputation: 10886

Vue.js pass callback through a prop.

I've got a component that looks like this:

<template>
    <div>
        <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination>
    </div>
</template>

<script>
    import Pagination from 'vue-bootstrap-pagination';

    export default {
        components: { Pagination },

        props: ['pagination', 'loadData'],

        data() {
            return {
                paginationOptions: {
                    offset: 5,
                    previousText: 'Terug',
                    nextText: 'Volgende',
                    alwaysShowPrevNext: false
                }
            }
        }
    }
</script>

In another component I use that ^:

<template>
    <pagination :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination>
</template>

<script>
 export default {
   loadData() {
       this.fetchMessages(this.pagination.current_page);
   }

   //fetchMessages
 }
</script>

But I receive the error:

Invalid prop: type check failed for prop "callback". Expected Function, got Undefined. 
(found in component <pagination>)

Is it not possible in Vue.js 2.0 to pass a callback?

Upvotes: 5

Views: 15679

Answers (2)

UnDroid System
UnDroid System

Reputation: 161

App.vue

<template>
  <div>
    <pre>{{ request }}</pre>
    <pagination @callback="loadData"></pagination>
  </div>
</template>

<script>
import Pagination from './Pagination.vue'
export default {
  name: 'App',
  components: { Pagination },
  data() {
    return {
      request: {}
    }
  },
  methods: {
    loadData(request) {
      this.request = request
    }
  }
}
</script>

Pagination.vue:

<template>
  <div>
    <button @click="$emit('callback', { currentPage: 10, whatEver: 7 })">call it back</button>
  </div>
</template>

<script>
  export default {
    name: 'Pagination'
  }
</script>

https://codesandbox.io/embed/8xyy4m9kq8

Upvotes: 4

Clorichel
Clorichel

Reputation: 2070

I think your second component may not be written accurately, your loadData callback should be in methods:

<template>
    <pagination :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination>
</template>

<script>
 export default {
   methods: {
     loadData() {
         this.fetchMessages(this.pagination.current_page);
     }
   }
 }
</script>

Upvotes: 5

Related Questions