Creating dynamic @click events in Vuetify using JSON objectsWould this rewrite be helpful for you?

I have a custom component that displays a dynamic list. Each page using this component can populate the list with different items.

<template>
  <v-list
    subheader
  >
    <v-subheader class="font-weight-black">Choose action</v-subheader>
    <v-divider/>
    <v-list-item
      v-for="(item, i) in model.menu"
      :key="i"
      @click="item.action"
    >
      <v-list-item-title>{{ item.title }}</v-list-item-title>
    </v-list-item>
  </v-list>

</template>

Additionally, here is the TypeScript class for this component.

<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import { app } from 'electron'

@Component
export default class ListItem extends Vue {
  @Prop() appStatus!: string
  @Prop() appId!: string

  model: any = {
    menu: [
      { title: 'Title One', action: 'someModalAction(appId)' },
      { title: 'Title Two', action: '' },
      { title: 'Title Three', action: '' }
    ]
  }

  someModalAction( appId: string ) {
    // show some modal here
  }
</script>

The model object is designed to be passed as a dynamic Prop() by other pages using this component.

However, I encountered an issue where clicking on "Title One" does not trigger the expected action. By modifying the object to include this.someModalAction(this.appId), the modal successfully appears on page load. But after closing the modal, the list item becomes unresponsive.

How can I dynamically pass actions to the @click event handler?

Answer №1

transforming information using getter method:

import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import { app } from 'electron'

@Component
export default class ListItem extends Vue {
  @Prop() appStatus!: string
  @Prop() appId!: string

  model: any = {
    menu: [
      { title: 'Title One', action: 'someModalAction' },
      { title: 'Title Two', action: '' },
      { title: 'Title Three', action: '' }
    ]
  }
  get items(){
    return this.model.menu

    .map(item => ({...item, action: item.action && () => this[item.action](this.appId)})
  }

  someModalAction( appId: string ) {
    // display a modal window 
  }
<template>
  <v-list
    subheader
  >
    <v-subheader class="font-weight-black">Select an action</v-subheader>
    <v-divider/>
    <v-list-item
      v-for="(item, i) in items"
      :key="i"
      @click="item.action"
    >
      <v-list-item-title>{{ item.title }}</v-list-item-title>
    </v-list-item>
  </v-list>

</template>

Answer №2

It's a good idea to create a single function to handle function calls on click events.

If you want to dynamically call functions, it's recommended to create a helper function that takes the function name as an argument and then invokes the corresponding function.

data () {
  return {
    test: '',
    submitting: false,
    list: [{
        title: "One",
        action: "itemClicked"
      },
      {
        title: "Two",
        action: "itemClicked2"
      },
      {
        title: "Three",
        action: "itemClicked3"
      }
    ]
  }
},
methods: {
  itemClicked() {
    alert('item clicked')
  },
  itemClicked2() {
    alert('item clicked 2')
  },
  itemClicked3() {
    alert('item clicked 3')
  },
  functionCall(name){
    this[name]();
  }
}

Check out the codepen demo for reference - https://codepen.io/Pratik__007/pen/JjoVxbj?editors=1010

Answer №3

v-list-item v-for="(item,index) in profileItems" @click="item.action" ripple="ripple"
                           :key="index">


{
          icon: 'mdi-exit-to-app',
          href: '/',
          title: 'Logout',
          action: () => {
            this.onUserLogout()
          }
        },
      ]

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

A guide to eliminating duplicate values within an array and across multiple arrays with the help of jQuery

Looking for assistance with jQuery to find and alert repeated values in my code. Below are example arrays: a1 = {1,2,3,4,5,6,4} a2= {9,8,7}, a3= {a,b,c,d,e,7} I want to identify the value 4 in array "a1" and give an alert, as well as identify the value ...

Adjust jqGrid dimensions automatically as browser window is resized?

Does anyone know of a method to adjust the size of a jqGrid when the browser window is resized? I attempted the approach mentioned here, but unfortunately, it does not function correctly in IE7. ...

The passport authentication process is currently stalled and failing to provide any results

The current authentication process is functioning properly app.post('/login', passport.authenticate('local-login', { successRedirect: '/home', failureRedirect: '/login', failureFlash: true }) ); Howev ...

Keep image height consistent and prevent resizing

I've hit a roadblock while trying to find a solution for this issue. There must be an easy fix that I'm overlooking... The problem arises when viewing the table with flags on a small screen (on mobile) - the image on the left seems to get sligh ...

The useEffect hook is failing to trigger within the Higher Order Component (Hoc

My component was working fine without using a HOC, but now that I've wrapped it inside withSpinner HOC, the fetching process does not start. const CollectionPage = (props) => { const { isCollectionLoaded, isCollectionFetching } = props; useEf ...

Terminate a remotely shared ngrok session that is forwarding a React application

My coworkers and I share an ngrok account while developing a React application using 'npx create-react-app' on UNIX-like systems. Occasionally, when trying to spin up an HTTP tunnel, I encounter the message: Your account '*****@*********.com ...

The jQuery validation applied to the data submission per post is not functioning as expected as the $_POST variable is appearing empty

I'm facing an issue with Jquery, AJAX, and field validation. Although the validation and redirect are working fine, I'm having trouble retrieving values from fields in the $_POST array. Below is the start tag of the form: <form class="smart ...

Prevent unwanted bouncing and zooming on IOS10+ when using routing in VueJS

Currently, I am developing a Vue.js application that integrates with Three.js to display 3D models. I am using Vue.js with Vuetify as the framework and incorporating the Vue.js router. Due to the nature of displaying 3D models, I need to prevent zooming i ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

Is it possible to combine several objects into a single array in JavaScript and determine the total number of objects within it?

Here is a snippet of code I am working with: {bloodStores && bloodStores.map((store) => { if ( store.status === "Stock" && store.b ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

Synchronizing two dropdown menus in Angular

I'm having trouble with binding and synchronizing select elements. I am trying to make two select elements work together, but using ng-value="$index" doesn't seem to be doing the trick. These are in sync: <select ng-model="myVar1"><op ...

Issue with jqGrid Multiple Selection

When constructing my jqgrid, I utilize the following code: multiselect: true This enables a check all column. However, clicking the check all checkbox (located at the header) selects all checkboxes, but does not click the checkboxes in each row. You can ...

What is the process of creating groupings within a list using jQuery?

Looking for help with creating sorted groups in jQuery. Here is my code snippet: https://jsbin.com/xabohupuzu/edit?html,js,output $(function(){ var data =['c','d','c','abc','dee','pu','gu& ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...

Replace the current picture with a newly uploaded one and keep it consistent

On my webpage, there is an image that I want to be able to replace by clicking on it and selecting a new image from the file uploader without showing the upload button. Once the new image is uploaded, I'd like it to replace the current image, and for ...

Enhance Vaadin 14: Automatically adjust TextArea size when window is resized

Using Vaadin 14.1.19 in a project called "My Starter Project," I attempted to create a TextArea that supports multiple lines. Initially, everything seemed fine, but upon resizing the TextArea, it failed to adjust the number of visible lines. Here is the co ...

What is the best way to remove a scrolling event handler from a particular element or class in JavaScript?

My goal is to set up a Table of Contents (TOC) in Obsidian that remains visible as you scroll through the page. Everything functions properly until you reach about halfway down the page, at which point the TOC mysteriously vanishes. #TOC, .TOC { posit ...

Using Vue to showcase the result of a form submission on a separate page

Working with a <form> in the context of vue has been successful as I am able to send the form data to the server, receive a JSON response, and print it on the console. However, my current challenge involves displaying this JSON response on a differe ...

Deploying a Vue.js project to Azure using GitHub Actions was unsuccessful

I need assistance deploying my Vue.js app to Azure using GitHub Actions. The workflow file generated by Azure was pushed to GitHub, but I encountered the following error: Failed to find a default file in the app artifacts folder (dist). Valid default fil ...