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

Is there a way to convert a JavaScript object to a class while eliminating unnecessary properties?

In my current project, I am using Typescript with ExpressJS to build APIs. Let's say I have a typescript User model defined as follows: class UserModel { id: number; email: string; password: string; name: string; dob: Date; ge ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

Error in clientWidth measurement providing inaccurate width

I recently adjusted the width of an image (img tag) to be 1150px * { margin: 0; padding: 0; box-sizing: border-box; user-select: none; } #background-image-myos { border: 2px solid black; border-radius: 5px; width: 1150px; } Sur ...

Revise the Event Handlers as the DOM structure evolves

Similar Question: Tracking DOM changes in JavaScript I am working with backbone.js and dynamically generated templates. In addition, I am utilizing multiple jQuery UI plugins that interact with specific classes, such as slimScroll: $(function(){ $(& ...

react-ga4 is sending multiple view events repeatedly

After setting up a Google Analytics account and creating a new property, I integrated the tracking ID with react-ga4 for my Album ItemPage as shown below: const ItemPage = () => { const {user} = useContext(AuthContext); let { item } = useParams ...

An error was encountered while attempting to proxy the request [HPM]

After cloning a GitHub repository, I ran npm i in both the root directory and client directories. I then created a development configuration file. However, when attempting to run npm run dev, nodemon consistently crashes with a warning about compiled cod ...

Utilize Ag Grid to selectively apply borders between grouped values

I have included my Plunker link: [https://plnkr.co/edit/lnF09XtK3eDo1a5v] Is there a way to add borders between different group values? For example, in this case, 'country' is the group and when all rows for United States are completed, can we a ...

Encountering difficulties in the installation of vuemdb

Currently, I am in the process of following the installation instructions for a newly created Vue application utilizing advanced installation steps. vue create project # include router and select vue 3 cd project vue add mdb # opt for free version # after ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Displaying Angular JS data in the Laravel application using the URL::route facade

I'm currently working on an Angular JS + Laravel Application. On one of the pages, I have a list of users that I fetch, and when a row is clicked, it redirects to the edit user page. Below is a snippet of my code: Blade Template <tbody> &l ...

Animate the div only when the button is clicked

I need a way to hide the text inside a div when it exceeds a certain height, but then expand it to full height upon clicking a button. However, I want this action to only affect the parent div of that specific button, rather than all the divs on the page. ...

Discovering time overlaps with Javascript and moment.js

In my calendar project, I am storing events for a day in an array. The start and end times are stored as String values in the following format: Example of events in a day const events = [{ "_id": "5bdf91a78197f0ced6c03496", "user": "5bd62237d6 ...

Is Babel necessary for a Node.js server application, and what are the benefits of using it?

My fondness for ES6 syntax and its new object-oriented style makes coding much easier for me. However, as a newcomer to JavaScript, I am curious about the advantages and disadvantages of using Babel in terms of performance, maintenance, readability, and ...

Leveraging Nuxt.js with Axios on Google Firebase hosting

When I deploy my project to Firebase hosting, I encounter an issue with the axios baseURL and/or proxy settings defaulting to local values instead of the ones specified in the nuxt.config.js. This results in 404 errors. Although hardcoding my URLs resolve ...

What could be causing the format to be incorrect?

docker run -it -v "%cd%":/e2e -w /e2e cypress/included:6.2.1 --browser chrome When attempting to execute this command within Visual Studio Code, an error is encountered: docker: invalid reference format. See 'docker run --help' Vario ...

Creating a personalized news feed using getstream.io in Node.js - a step-by-step guide

const stream = require('getstream'); // Setting up a newsfeed stream using getstream const client = stream.connect( null, ); // Defining a feed for user1 var user1 = client.feed('user', 'user1'); // Adding a custom activity ...

Using TypeScript to determine the week number - the value on the right side of the math operation must be of data type 'any'

I've spent a lot of time searching for code to help me calculate the week number in my Angular app according to ISO standards. It's been challenging to find JavaScript-specific code, but I believe I may have found something - however, I encounter ...

Display only distinct items in a v-for loop in Vue.js

I am attempting to show icons based on specific v-for and v-if conditions. However, the icons are appearing multiple times when I only want them to display once. I attempted using v-if = 'index === 0', but this did not resolve the issue. <di ...

The toggle button for columns is not triggering the callback action

When working with the following JSFiddle, I noticed that the action function does not seem to fire whenever a button to select a column in the column visibility tool is selected. Check out the code snippet below for reference: $(document).ready(function( ...

Customize the URL path in Next.JS according to the user's location

My Next JS website is hosted on the domain abc.com. I would like the site to automatically detect a visitor's location, retrieve their country code, and then redirect them to abc.com/country_code. ...