Using Vue.js to summon a method from within a data property in a component

Can component methods be assigned to data variables using the example code below? It seems it is not working correctly. What could be the right way to do this?

<li v-for="item in items" @click="item.action">
    {{ item.title }}
</li>
export default {
    data: () => ({
        items: [
            { title: "One", action: this.funcOne },
            { title: "Two", action: this.funcTwo },
        ]
    }),
    methods: {
        funcOne() {
            alert("Hi")
        },
        funcTwo() {
            alert("Hello")
        }
    }
}

Answer №1

It is suggested to pass the Vue instance (this) as a parameter to the data function data: (vm) =>, and then utilize it like so: action: vm.funcOne

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
      data: (vm) => ({ // Use vm as the component instance this
        items: [
            { title: "One", action: vm.funcOne },
            { title: "Two", action: vm.funcTwo },
        ]
    }),
    methods: {
        funcOne() {
            alert("Hi")
        },
        funcTwo() {
            alert("Hello")
        }
    }
  })
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
<li v-for="item in items" @click="item.action">
    {{ item.title }}
</li>
</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

Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly. Let me share the relevant ...

Modifying the temp variable by assigning a new value to this.value in Javascript

Using a temporary variable, I initialize a THREE.Vector3 which is then passed into the creation of an object. object[i] = new Object(new THREE.Vector3(0,0,0)); Within the Object class, there is a variable called texture that gets assigned the new THREE.V ...

Executing asynchronous code in a sequential manner

I'm encountering a problem. I have an AngularJS function that calls another AngularJS function which includes a POST request. The issue is that this POST request always fires last, once the first function has completed. It doesn't execute sequent ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

What is the technique for integrating a required file into an Angular module using Browserify?

My Angular SPA build is set up to use NPM for calling the browserify script to bundle it. To execute the build process from the terminal, you can run npm run build:js, which triggers the following script in the package.json file: "build:js": "browserify - ...

Upload a user-sent image to a remote SFTP server for safekeeping

Can someone help me figure out how to upload a file to an SFTP remote server using ssh2-sftp-client? I am trying to retrieve the file from the user via a post request along with the destination. To process the file, I am utilizing multer. const Client = r ...

Utilizing Database values in .css files with Vue.js and TypeScript

I am currently working on extracting a color value from the database and applying it to my external .css files. I have searched extensively online but haven't found a satisfactory solution yet. Here is the JavaScript code snippet: createBackgroundHead ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

Navigate to a different page in Vue using Nuxt's scroll-to feature

I am currently working on implementing a menu that allows for smooth scrolling to different section ids. Everything is functioning well when I scroll within the same page, but I run into issues when trying to navigate to sections on other pages with the s ...

Struggling with transferring form input data to a different file using JavaScript, Node.js, React.js, and Next.js

I've been struggling with writing form input to a separate file in JavaScript. I created a demo repo to showcase the issue I'm facing. Check it out here: https://github.com/projectmikey/projectmikey-cant-write-to-api-dir-stackoverflow Locally, t ...

"Embracing the power of Angular's scope

Currently working through a tutorial with Angular and utilizing this version of the framework: https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js[1] This is my current template setup: <div ng-controller="ParentController"> <div ...

What is the best way to make a request to the deployed API on Vercel?

Here is the structure of my files: root client index.js package-lock.json package.json routes.js Upon sending a request to my API, I receive a status code of 200 but an error message stating "You need to enable JavaScript to run this app." Both ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

Console log showing no response from AJAX request

For my group project, I've been working on setting up an API to display a response in the console log. After troubleshooting and fixing errors, I am still not seeing any response when I click submit. JavaScript var zipcode = ""; function localMovie ...

Using JavaScript to Set Values and Manage Session State in APEX

Trying to utilize JavaScript in Oracle APEX to set the value and session state. See below function that is being called: function updateItemValue(element) { $s('P2020_SELECTED', element); apex.server.process ('MY_PROCESS', { ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Switching off toggle does not switch back to primary theme when clicking again for the second time

When I click the button for the first time, it changes the theme. However, when I click it a second time, nothing happens; it seems like it's stuck on the second theme forever. It should change themes with every click. Can someone please help me with ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...