Ways to attach dynamic methods within a v-for loop

I am currently working on a situation where I need to dynamically assign methods to elements that are being generated by a template using a v-for loop. These methods will be assigned based on the value of a particular variable, specifically the 'btn.method' variable in this case. Is it actually feasible to achieve this?


var formButtons = new Vue({
    el: "#formButtons",
    data: {
        buttons: [
            {
                id: "login",
                text: "Login",
                method: "submitForm"
            },
            {
                id: "cancel",
                text: "Cancel",
                method: "clearForm"
            }
        ]
    },
    methods: {
        submitForm: function (event) {
            // Some Code
        },
        clearForm: function (event) {
            // Some Code
        }
    },
    template: `
    <div>
        <div class="form-group"  v-for='btn in buttons'>
            <button
                v-bind:id='btn.id'
                v-on:click='btn.method'
            >
                {{ btn.text }}
            </button>
        </div>
    </div>
    `
});

Previously, I tried passing the method name as a string but encountered an error message stating, "TypeError: e.apply is not a function.".

My goal is to have each button associated with its own specific method, for instance:
  - Login button => submitForm method
  - Cancel button => clearForm method

Answer №1

Could you please attempt this:

let controlPanel = new Vue({
    el: "#controlPanel",
    data: {
        elements: [
            {
                id: "start",
                text: "Start",
                action: "beginProcess"
            },
            {
                id: "stop",
                text: "Stop",
                action: "endProcess"
            }
        ]
    },
    methods: {
        beginProcess: function (event) {
            // Insert your code here
        },
        endProcess: function (event) {
            // Insert your code here
        },
        handleClick(actionName) {
            this[actionName]()
        }
    },
    template: `
    <div>
        <div class="control-group"  v-for='elem in elements'>
            <button
                v-bind:id='elem.id'
                v-on:click='handleClick(elem.action)'
            >
                {{ elem.text }}
            </button>
        </div>
    </div>
    `
});

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

Creating prototypes for objects starting from an empty state

Below is the custom code structure I have created: module.exports = (function() { Function.prototype.extend = function(obj) { for (var prop in obj) { this[prop] = obj[prop]; } } })(); var CustomHelpers = {}; CustomHelpers.prototype.get ...

Exploring Laravel 4: Controlling AJAX data manipulation via the controller

I am a beginner in using Laravel and ajax. Currently, I am working on retrieving data from a form through ajax and calling a controller method using ajax as well. The controller method searches the database and returns a json response to be handled by ajax ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

Displaying Font Awesome icon within a loop in a Vue.js component

I am trying to display icons within a v-for loop. The data for the links and icons is stored in a JSON file. However, I am facing an issue when trying to use Font Awesome icons with Vue.js. When I include Font Awesome via CDN, everything works fine. But wh ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

Troubleshooting: Issue with passing variables from jQuery $.ajax to PHP

I am working on creating a 'show more' button using jQuery AJAX. The button has a loaded attribute like this: <button type="button" class="smbt btn center-block" data-loaded="3">Show More</button> In my JavaScript file, I have the f ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

"Encountering a KnexTimeoutError while utilizing the knex.transactionProvider() function

I am currently working on implementing Knex transactions into my project using the relevant files provided below. However, I am encountering the following error: KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you ...

Check to see if the menu item exceeds the allotted space, and if so, display the mobile menu

Currently, I am in the process of creating a unique responsive menu for my website that I think will need some JavaScript implementation. My skills with JavaScript are not very strong, so I am looking for guidance, code examples, or resources that can assi ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

What is the best way to display an Error 404 page in a statically rendered client-side page using Next.js?

import { onAuthStateChanged } from "firebase/auth"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { auth } from "../../lib/firebase&qu ...

What are some creative ways to design the selected tab?

In my Vue parent component, I have multiple child components. There are several elements that toggle between components by updating the current data. The issue is that I am unsure how to indicate which tab is currently active. I've tried various li ...

Troubleshooting Vue.js unit test issues caused by log messages from internal components

I am working with a component structured like this: <template> <p>{{ message }}</p> <internal-comp></internal-comp> </template> <script> import InternalComp from './components/InternalComp.vue'; ...

Developing desktop applications with Angular 2 using NWjs

Looking to create an Angular 2 Desktop App using NWjs. Where can I find the entry point? Could someone provide some examples of developing Angular 2 Desktop Apps with NW.js? ...

Vanilla JavaScript: Enabling Video Autoplay within a Modal

Can anyone provide a solution in vanilla JavaScript to make a video autoplay within a popup modal? Is this even achievable? I have already included the autoplay element in the iframe (I believe it is standard in the embedded link from YouTube), but I stil ...

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

Looking to enhance code by using jQuery to substitute numerous href elements. Only seeking enhancements in code quality

I am currently using regular JavaScript to change the href of 3 a-tags, but I want to switch to jQuery for this task. var catNav = $('ul.nav'), newLink = ['new1/','new2','nwe3/']; catNav.attr('id','n ...

Placing content retrieved from a MySQL database within a form displayed in a ColorBox

Having difficulty inserting text from a MySQL database into a form (textfield) inside a ColorBox. The current script is as follows: <a href="#" class="bttn sgreen quote1">Quote</a> var postQuote[<?php echo 4id; ?>]=<?php echo $f ...

Steps to set up Feathers instance in Jest environment once

When running Jest tests, I want to utilize only one instance of feathers "app" throughout. This is how I currently import app in each test: const app = require('../../src/app'); describe(`service`, () => { it('registered the service&ap ...

Reduce the amount of time it takes for a Google AdWords Script to generate a

According to Google Script best practices, it is recommended to store operations in an array and then call the methods once all the operations have been constructed. This helps minimize response time each time a service is called. For example, let's ...