using vuejs to pass a function as a prop

As I work on creating a foundational "TableComponent," incorporating selectable rows and more, I am faced with the requirement for this TableComponent to accept a prop named "buttons."
These buttons are expected to be in the form of an array of objects structured like this:

buttons: [{
    label: 'Manage Themes',
    click: () => {
        if(this.selectedRows.length) {
            this.$router.push({ name: 'ManagePageOptions', query: { concernable_type: this.type, concernable_ids: this.selectedRows.map(row => row.id).join(',') }});
        } else {
            alert('Please select 1 or more company or user');
        }
    }
}]

To render a row of buttons within the table component based on the provided input, the following logic is implemented:

<b-button v-for="button in this.buttons" @click="button.click" :key="button.label"> {{ button.label }} </b-button>

However, a challenge arises when accessing the selected rows data within the click function of these buttons, as "this" pertains to the parent component.

UPDATE: A solution has been discovered where passing "this" as a parameter to the click function resolves the issue. The question remains about its appropriateness.

buttons = [{
    label: 'Manage Pages',
    click: (vm) => {
        if(vm.selectedRows.length) {
            vm.$router.push({ name: 'ManagePageOptions', query: { concernable_type: vm.type, concernable_ids: vm.selectedRows.map(row => row.id).join(',') }});
        } else {
          alert(Lang('Please select 1 or more company or user'))
        }
    }
}];

Data for the TableComponent:

data() {
    return {
      selectedRows: [],
      m_this: this,
    };
  },

_

<b-button v-for="button in this.buttons" @click="button.click(m_this)" :key="button.label"> {{ button.label }} </b-button>

Answer №1

While I agree with the suggestions for utilizing scoped slots as a better alternative, if you are determined to pass functions in this manner, there are steps you need to take:

  1. Redefine your handler from click: () => {} to click: function() {}. This is necessary because the usage of this behaves differently in arrow functions and may result in it being bound to the parent Vue component.

  2. When passing the handler into the button component within the template of TableComponent, ensure that you bind the handler to the this of your TableComponent, following the guidance provided in this resource.

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

In order to ensure that the program runs continuously, it is essential to confirm that an event has not already occurred before exiting the loop

In my Python program, I am attempting to search for a specific value within a table on a webpage. Using a function called Alert_Red, I can successfully retrieve the desired value. However, I am facing an issue where the values are being printed in an endle ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

I am struggling to grasp the concept of scopedSlots in vue.js

Help! I am new to vue.js and struggling with understanding scopedSlots and examples in the official guide. Can someone please provide a detailed explanation? Thank you! ...

Is there a way to make this AngularJS service wait until it has a value before returning it?

Multiple controllers call a service that loads data into an object named categories: .service('DataService', ['$http', '$q', function($http, $q) { var categories = {}; // Public API. return({ setCategory ...

The state object in Redux Toolkit remains static, resulting in the error message "Uncaught TypeError: Cannot assign to read only property 'property-name' of object '#<Object>'"

I'm facing an issue where I am trying to update the data of a state object in Redux Toolkit but it's not changing, and instead throwing an error that says Uncaught TypeError: Cannot assign to read only property 'status' of object ' ...

Stylized search input inspired by Pinterest with a bubbly design

When it comes to my search bar, I want the user's entered keywords to be displayed within a bubble that has a delete option when they press space to add another keyword. This functionality is similar to what Pinterest does with their search bar, as de ...

How can JavaScript be utilized for connecting to CSS files?

I'm unsure if this is feasible and after a brief search, I couldn't find any information. I am curious to know if it's possible to connect a CSS file using JavaScript? In essence, I would like to invoke a style sheet when I execute a specif ...

Implementing dynamic width with ng-style in AngularJS

I am trying to dynamically resize a div when an event is fired from S3. In the code below, I pass the progress variable to the updateProgress function as a parameter. This function resides in the top scope of my Angular controller. s3.upload(params).on(& ...

Eliminate the bottom border from the MUI Input component

Is there a way to get rid of the bottom-line borders on these input fields? I attempted using CSS but couldn't find a solution for this component -> <Input type={"text} /> ? https://i.sstatic.net/4QpWym.png ...

Displaying the chosen array in a Material UI Table within a React application does not show the desired checkboxes

After days of hard work and research, I finally figured out how to achieve what I needed. In my React App, I have a Material UI table that I want to load with pre-rendered checks in the DOM based on entries in a selected array. The selected array contains ...

Unable to retrieve a string from one function within another function

Three functions are responsible for triggering POST API calls, with the intention of returning a success or failure message to whoever invokes them (Observable<string>). In an effort to avoid repetition, I introduced a new function to retrieve succe ...

Navigating programmatically to another page in Next.js can be easily achieved by utilizing the useRouter hook

Following a post request to an external API, my goal is to navigate back to the homepage. While I am familiar with React, this is my first experience using Next.js. Here's the snippet of code: export default function New({genres}) { const createMovie ...

Step-by-step Guide: Building a Nested Bootstrap Navigation Tabs Component on a Webpage

Within a page, I have integrated nested bootstrap navs components. The issue arises when clicking on "Nested Tab 2," which functions correctly, and then switching to "Nested Tab 1" where the tab content is not displaying properly. I am uncertain if there ...

What is the best approach to creating a versatile JavaScript module that can be easily customized for various scenarios?

I am in the process of developing a JavaScript module that will submit data via an AJAX request when a button (next or previous) is clicked at the bottom of a modal. Once the data is submitted, the next modal out of a total of 4 will be displayed. The cha ...

Unable to invoke JS function in Drupal 5 file

In my current project using Drupal 5, I have a specific .js file that is included using the code: drupal_add_js(drupal_get_path('module','MTM')."/include/JS_form.js"); Additionally, there is an element on the page: <a onclick="MTM ...

Internet Explorer failing to trigger Ajax requests

I'm encountering an issue with my script on my webpage - it works perfectly in Chrome, but Internet Explorer is not entering the success{} function of Ajax. It does go into the Complete{} function without any problems. I attempted to pass the data var ...

Axios JWT fails to transmit

I am currently working on a project that has two layers - the back-end is developed using Spring Boot with security measures in place such as Sprint Security and JWT, while the front-end is built using Vue.js with Axios library for inter-layer communicatio ...

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...

Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express ...

JavaScript: Implementing a retry mechanism for asynchronous readFile() operation

My goal is to implement a JavaScript function that reads a file, but the file needs to be downloaded first and may not be immediately available. If an attempt to access the file using readFile() fails and lands in the catch block, I want to retry the actio ...