Is there a way in Vue.js for me to access a method from within the same component using the component's data?

Below is the code for a specific component:

<template>
   <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //attempting to call the method in the component
      {{menu.title}}
   <li>
</template>
<script>
export default {
        data: () => ({
            menu: [
                {title: 'Start Preparing', action: this.startPrepare}, //how do I reference the method here?
                {title: 'Cancel Order'},
            ],
        }),

        methods: {
            startPrepare: function (orderId) {
                console.log("start")
            }
        }

    }
</script>

The menu section in the data part includes both title and action properties. The goal is to trigger the specified function when an item is clicked within the template.

The challenge lies in referencing a method from the same component in the data section. Currently, there's an error indicating that startPrepare is undefined.

Please let me know if you need further clarification.

Answer №1

One issue that stands out is the use of an arrow function for the data, which can cause problems binding to the Vue instance. Consider using a regular function instead ..

export default {
  data() {
    return {
      menu: [{
          title: 'Start Preparing',
          action: this.startPrepare
        }, //how do I reference the method here?
        {
          title: 'Cancel Order'
        },
      ],
    }
  },
  methods: {
    startPrepare: function(orderId) {
      console.log("start")
    }
  }

}
<template>
    <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //trying to call the method in the component
        {{menu.title}}
    <li>
</template>

Answer №2

One way to incorporate the method name as a string in your Vue template is by setting it as a property in the data object and accessing it using

@click="handleAction(item.action)"
:

<template>
   <li v-for="(item, i) in menu" :key="i" @click="handleAction(item.action)">
      {{menu.title}}
   <li>
</template>
<script>
export default {
        data() {
            return {
                menu: [
                    {title: 'Start Preparing', action:'startPrepare'}, //how do I reference the method here?
                    {title: 'Cancel Order'},
                ],
            };
        },
        methods: {
          handleAction(actionName){
          this[actionName]();
           },
           startPrepare(orderId) {
              console.log("start")
           }
        }

    }
</script>

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

Tips for implementing a selection event in an auto complete dropdown menu:

I am struggling with detecting the selection in this Combobox. For example, if I choose "Massachusetts", I want to be able to access that information. @change call API + populated list - Done ✅ @select doSomething() - Not Done ❌ I have a hard time d ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

Preventing page navigation in JavaScript: Why it's so challenging

I am encountering an issue with a link element that I have bound a click event to (specifically, all links of a certain class). Below is an example of the link element in question: <a id="2" class="paginationclick" style="cursor: pointer;" href=""> ...

Maintain the selected image

I am working on a program that allows users to choose images and I have given them the pseudo-class. .my_image_class:hover{ border:3px solid blue; -webkit-box-sizing: border-box; } This makes the images bordered in blue when hovered over, giving a "sele ...

What does React default to for the implementation of the ``shouldComponentUpdate`` lifecycle method in its components?

Having a personalized approach to the shouldComponentUpdate() method as part of the React component lifecycle is not obligatory. I am aware that it serves as a boolean function determining whether the render() function will be triggered by changes in comp ...

"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items: <script type="text/javascript> jQuery(function(){ jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){ var current ...

Swap out the svg element with an icon alternative

Transforming Circle Elements into Shopping Cart Icons I am attempting to change the appearance of my SVG circle elements to resemble shopping carts. Is there a method to completely alter the definition of a circle element in svg so that it displays a spec ...

Passing a PHP variable between PHP files with the help of jQuery

I'm facing a minor issue. I'm trying to pass a PHP variable from one PHP file to another using setInterval. However, I'm unsure of how to include the PHP variable in my jQuery code. Here is the content of first.php: <?php $phpvariable= ...

What is a better alternative to using the Event Bus for inter-component communication: data and computed properties

In the context of myComponent, there is a button that triggers the openOverlay function when clicked. This function emits an event called openedOverlay via EventBus. <button @click="openOverlay" </button> <Overlay /> methods: { openOver ...

PHP is unable to show items containing special characters such as double quotes and apostrophes

I am facing an issue with ordering food items. Names that do not contain apostrophes work fine, but those like Pasqua Nero D'Avola Sicilia are causing problems. I have tried replacing ' with \', but the issue persists. Here is the relev ...

Developing an animated feature that displays a dynamic count up to the current size of the browser window

I have a script that's able to determine the height and width of my browser window. However, I am facing a challenge in creating a way for these dimensions to count up from zero to their current values upon loading. The desired functionality would be ...

Is there a way to turn off predictive text for reCAPTCHA on my mobile device?

Using reCAPTCHA on a sign-up form can get frustrating on mobile devices, with constant dictionary word suggestions while typing. I am aware of how to disable this feature for normal input fields by adding attributes through JavaScript, but shouldn't ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

"Adjusting the position of the Icon in the Material UI ItemList to make it closer

How can I bring this icon closer to the text? I'm not sure how to do it. When I enter developer mode, it shows me this. https://i.stack.imgur.com/WzhB1.png I am uncertain about what the purplish stuff indicates. My objective is to move the icon to t ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

Import ES6 code by wrapping it in parentheses

Currently delving into React Native and I'm intrigued by the parentheses used in the first line of import. import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorldApp extends Co ...

Ensuring the Accuracy of POST Parameters Using Express-Validator

I've been working on adding parameter validation to my Node/Express API by utilizing express-validator. However, I encountered a situation where even though I sent a POST request with a missing "name" field using the curl command curl -X POST -d "foo= ...

Design my div layout to resemble a tree shape

Take a look at this URL. I have dynamically created divs in a nested structure for a sports tournament. I need help styling the divs to match the tournament structure. This is how I want my structure to look. The code is functioning properly, it's ju ...