Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way:

<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: 'Previous',
                    nextText: 'Next',
                    alwaysShowPrevNext: false
                }
            }
        }
    }
</script>

In another part of my project, I am utilizing the above component as follows:

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

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

   //fetchItems
 }
</script>

However, when implementing this, I encounter the error message:

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

Does Vue.js 2.0 not support passing a callback function?

Answer №1

It appears that there may be an issue in the way your second component is written. It seems like your loadData callback needs to be defined within the methods section:

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

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

Answer №2

MainComponent.vue

<template>
  <div>
    <pre>{{ requestData }}</pre>
    <custom-pagination @callback="retrieveData"></custom-pagination>
  </div>
</template>

<script>
import CustomPagination from './CustomPagination.vue'
export default {
  name: 'MainComponent',
  components: { CustomPagination },
  data() {
    return {
      requestData: {}
    }
  },
  methods: {
    retrieveData(request) {
      this.requestData = request
    }
  }
}
</script>

CustomPagination.vue:

<template>
  <div>
    <button @click="$emit('callback', { pageNum: 5, optionalParam: 'example' })">trigger callback</button>
  </div>
</template>

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to include custom headers in the response of socket.io using express.js?

I have been attempting to override the CORS policy using the following code block: app.use('/\*', function (req, res, next) { res.header("Access-Control-Allow-Origin","*") res.header("Access-Control-Allow-Hea ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

How to retrieve a DOM element using Aurelia framework

When it comes to accessing a DOM element in Aurelia, what are the best practices to follow for different use cases? Currently, I have two scenarios in my Aurelia project: Firstly, within the template, there is a form that I need to access from the view-mo ...

``Changing the value of the radio button does not update the ng-model variable

I have encountered an issue with my code. Upon page load, the radio button is checked but the ng-model value session.payment does not get updated automatically. I have to manually select it again for the update to take effect. <li ng-repeat="method i ...

"Integrating JavaScript in C# Code Behind: A Step-by-Step Guide

Is there a way to trigger this javascript function using C# code in the backend when the page loads? Your assistance is greatly appreciated, thank you. <script type="text/javascript"> document.onkeydown = function (event) { event = ( ...

Vue.js creates a new row in the table with an undefined array of data

Trying to create a new row when clicking "+" using Vue Js Encountering an error: tablerows is not defined Vue.component('inp-row', { props: ['data'], template: `<tr :id="data.row_id" ><td> 1</td><td>2 < ...

Guide on incorporating text onto objects with three.js

I successfully incorporated text into my shirt model using a text geometry. Check out the code below: var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = 'italic 18px Arial'; ctx.te ...

Choosing an element from an array in JavaScript that meets a certain criteria

How can I isolate an object from an array where the value for the "slug" key is "A"? For instance, consider the following data: var allItems = [ { "slug": "henk", "company_founded": "2008", "company_category": "Clean", ...

FancyBox - Is there a "Never show this message again" option available?

I implemented FancyBox on my website to display important information to users. However, I would like to enhance the user experience by adding a button that allows them to set a cookie and prevent the message from popping up for about a month. Since I&apo ...

Trigger price update in jquery based on radio or checkbox selection and specific conditions

https://i.sstatic.net/OIvgF.png In my product form, I have implemented a feature where selecting the "product type" and "product size" will update the price. However, if the user changes the product type after selecting the size, the price does not update ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

Webpack is throwing an error stating that it cannot find a module with the relative path specified

Here is the structure of my app (excluding the node_modules directory): ├── actions.js ├── bundle.js ├── components │   ├── App.js │   ├── Footer.js │   ├── Link.js │   ├── Todo.js │   └─ ...

Using ReactJS to search for and replace strings within an array

A feature of my tool enables users to input a string into a textfield and then checks if any words in the input match with a predetermined array. If the user's string contains a specific name from the array, I aim to replace it with a hyperlink. I&a ...

Error possible in modal due to interaction between JavaScript, PHP, and Bootstrap - Unable for PHP file to successfully retrieve value from JavaScript file

I have an existing database that is already populated. Additionally, I have a JavaScript function that captures the ID of the element when a button is pressed. Here's an example: Name of Subject | Actions -------------------------------------- ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...

Tips for sending custom props to a dynamic page in Next.js

I have created a component called Card.js which is responsible for linking to dynamic pages when a card is clicked. My goal is to pass a value, such as 'category', to the dynamic page [id].js so that I can implement additional logic there. Card. ...

The sorting icons fail to display in a customized VDataTable when using Vue 3 and Vuetify 3

Currently, I am in the process of converting my project from Vue 2 to Vue 3 along with upgrading Vuetify to the latest version. The existing VDataTable component in Vuetify is sourced from Vuetify Labs. While the data table functions properly, the sorting ...

What is the syntax for creating a for loop in JSX within a React component?

I am working on a simple program that involves using a for loop to print numbers from 0 to 10. My goal is to utilize a for loop to print these numbers and pass the props to a child component. Please see my code below: import React, { Component } from &apo ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...