What is the process for dynamically setting @click in vue.js?

My array contains objects with methods as actions from a vue object.

How can I dynamically set the @click event in a v-for loop?

I attempted to use this.m1, "this.m1", "m1", but encountered an error:

fns.apply is not a function.

Javascript:

new Vue({
  el: "#app",
  data: {
    items: [
      { title: "Learn JavaScript", action: this.m1 },
      { title: "Learn Vue", action: "m2" },
      { title: "Play around in JSFiddle", action: "this.m3"},
      { title: "Build something awesome", action: "m4"}
    ]
  },
  methods: {
    m1() {
        console.log('1');
    },
    m2() {
        console.log('2');
    },
    m3() {
        console.log('3');
    },
    m4() {
        console.log('4');
    },
  }
})

Html:

<div id="app">
   <div v-for="item in items">
       <a @click="item.action" href="#">
         {{ item.title }}
       </a>
   </div>
</div>

Demo - https://jsfiddle.net/mezhevikin/eywraw8t/338303/

Answer №1

If you save the method names in the action property as shown here: action: "m1", you can pass those names to a method (let's say invokeMethod) using "invokeMethod(item.action)". Inside the invokeMethod function, you can then call the relevant functions by invoking this[methodName]() - this is like saying this["m1"].

var app=new Vue({
  el: "#app",
  data: {
    items: [
      { title: "Learn JavaScript", action: "m1" },
      { title: "Learn Vue", action: "m2" },
      { title: "Play around in JSFiddle", action: "m3"},
      { title: "Build something awesome", action: "m4"}
    ]
  },
  methods: {
    invokeMethod(methodName) {
        this[methodName]();
    },
    m1() {
        console.log('1');
    },
    m2() {
        console.log('2');
    },
    m3() {
        console.log('3');
    },
    m4() {
        console.log('4');
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
   <div v-for="item in items">
       <a @click="invokeMethod(item.action)" href="#">
         {{ item.title }}
       </a>
   </div>
</div>

Answer №2

Information must be integrated as a function

new Vue({
  el: "#app",
  data () {
    return {
      items: [
        { title: "Master HTML", action: this.m1 },
        { title: "Discover CSS", action: this.m2 },
        { title: "Experiment in CodePen", action: this.m3},
        { title: "Create something amazing", action: this.m4}
     ]
    }
  },
  methods: {
    m1() {
        console.log('1');
    },
    m2() {
        console.log('2');
    },
    m3() {
        console.log('3');
    },
    m4() {
        console.log('4');
    }
  }
})

See the demo here

Answer №3

To achieve your desired outcome, it is important to pass the item object through a single method and then perform operations accordingly.

var software=new React({
  el: "#software",
  data: {
    items: [
      { title: "Learn Python", action: "m1" },
      { title: "Learn React", action: "m2" },
      { title: "Experiment in CodeSandbox", action: "m3"},
      { title: "Create something amazing", action: "m4"}
    ]
  },
  methods: {
    executemethod(item) {
        console.log(item.action);
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/react"></script>

<div id="software">
   <div v-for="item in items">
       <a @click="executemethod(item)" href="#">
         {{ item.title }}
       </a>
   </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

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

Troubleshooting: Why is the AngularUI Modal dialog malfunctioning

I'm currently working on integrating an angularUI modular dialog into my application. Here is a snippet from my controller.js file: define([ 'app' ], function(app) { app.controller('TeacherClasses', [ '$scope', &apo ...

I am currently in the process of cross-referencing the tags that have been retrieved with those that have been selected or created. If a tag does not exist

I have a collection of tags in an object, and I want to dynamically add new tags before submitting the form. Despite using vue watch, it doesn't seem to be working for me. Here is the code snippet: data() { return { blog: { blog_ti ...

Display when moving up and conceal when moving down

Is there a way to make the div appear when scrolling up and down on the page? I'm new to jquery and could use some assistance, please. ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Eliminate the border and style of a link that was clicked before in a React/Next.js

I've created a function where clicking on an element adds borders using onClick trigger. Here's the code snippet from the component: import { useEffect, useState } from 'react'; import Link from 'next/link'; import Logo from ...

Display a 404 page on Vue router when the ID does not match

When it comes to displaying a 404 page if a parameter doesn't match, I'm a bit puzzled. For instance, if the user name is “joe” and someone tries to access “/joe/categories”, then the categories component should be displayed. Now, I want ...

Configure Protractor's configuration file to utilize a personalized reporter

I'm in the process of setting up end-to-end tests using protractor.js, but I am not happy with how the default reporter displays results on my terminal window. Is there a way to customize the reporter configuration to make it easier to read and more ...

Retrieve a zip file using React and Node from a RESTful API

I have an application built with React and Node where I have a table that includes a download button. Clicking the download button triggers a request to my Node app, which in turn should call a REST API to download a zip file directly into the browser. In ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Tips for displaying data using AJAX in Vuejs 2

When attempting to set data in a Vue instance, I encounter difficulties. For example, when assigning values to the data property via AJAX, I am able to render the exam object. However, I face an error when trying to access an inner array with exam.question ...

Switch between showing and hiding a div by clicking on the panel header and changing the symbol from + to

I need assistance with a panel feature on my website. The panel should expand when the "+" symbol is clicked, displaying the panel body, and the "+" symbol should change to "-" indicating it can be collapsed by clicking it again. There is a slight twist t ...

jQuery Mobile is experiencing page height inaccuracies

My web application, built with jQuery Mobile 1.2.0, is encountering an issue with page height calculations on Windows Phone. While iOS and Android display correctly, there is a gap at the bottom of the page on Windows Phone. Is there a CSS-only solution t ...

Explore the latest update in the AngularJS single page application that introduces a new feature specifically designed for the initial login

Our AngularJS single page application has a new feature that we are ready to launch for customer use. We want to inform the logged in user about this new feature so they can start using it. We are looking for a small animated information symbol with a too ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

The Vue component table is not showing any retrieved data

Seeking help as a newcomer to the world of Laravel and Vue.js. Trying to populate data on a Vue component, but facing an issue with the tableData variable in the axios.get response. It is not rendering the array data onto the table as expected. Could there ...