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

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

What is the best way to showcase the element of a chosen Id within vuejs?

I have a component named Home.vue with a router link that contains an id. When users click on this link, it redirects them to another page. How can I display the data elements associated with the clicked id? <li class="ta-track-card column ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

fetch the image data from the clipboard

Hey there! Is it possible to use JavaScript to retrieve an image from the system clipboard (Windows/Mac) and paste it into a website? ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Is there a way to determine the app bar height within a React Material UI application?

I'm trying to create a full-screen image for the opening of my website using React and Material UI. Here's a snippet of my JSX code with the default Material UI theme: <AppBar> //code in between </AppBar> <Container sx={{margin: ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

The link tag cannot be used inside a division element

I am facing an issue with a button that has three different states represented by images. While the button looks great and functions well, it fails to perform its primary function - linking to another document. Upon clicking the button, no action is initi ...

Implementing a delay between two div elements using jQuery

I have two Divs with the class "sliced", each containing three images with the class "tile". When I animate using jQuery, I am unable to add a delay between the "sliced" classes. However, I have successfully added a delay between the "tile" classes. index ...

Failing to retrieve data from Ajax response

When handling requests in a servlet, the following code snippet processes the request received: Gson gson = new Gson(); JsonObject myObj = new JsonObject(); LoginBean loginInfo = getInfo(userId,userPwd); JsonElement loginObj = gson.toJsonTree(loginInfo) ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

In Ember.js, where should I place the initialization code for a controller? I attempted to set it up in the routes

With my experience working with ember.js and highcharts, I have come across some examples that were too simplistic for me to grasp how to set up the chart objects and render them properly. I have explored initializers and understand the significance of ro ...

The event listener fails to function properly in asynchronous JavaScript

The reason for the error is due to the asynchronous nature of the code, where the button is not loaded yet. Is there a solution to this issue? It's difficult to explain in words but essentially, when the window is loaded, the button is not present as ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

I'm puzzled as to why this code snippet consistently produces a range of 50 to 100 repeated values. This piece of code is crucial for altering the behavior of a function based on a specific

Below is a snippet of my React code aiming to alter the functionality of a function based on a specific window width: const [windowWidth, setWindowWidth] = useState({ winWidth: 0 }); useEffect(() => { window.addEventListener('resize', ( ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...