Menubar: transfer item key parameter in command function

UI Components for Vue
Post Reply
sfranke
Posts: 2
Joined: 14 Mar 2023, 13:03

15 Mar 2023, 12:57

Hallo dear community,
I am a newby in Vue3 and PrimeVue.
I am working on a prototype app with a menubar.
My problem now is, that I am planing to have a general click function for all menubar items.
I will use the key option inside the click function to identify which item was clicked.
But I do not know how to pass this option as input parameter into this function.

This is how I declaired the items array and the click function for the menubar inside the <script> Tag

Code: Select all

    const items = ref([
        { 
            key: 1,
            label: "File",
            command: () => onMenuItemClicked(),
            items: [
                {
                    label: "Open Project",
                    icon: "pi pi-fw pi-file-import"
                },
                {
                    label: "Save Project",
                    icon: "pi pi-fw pi-file-export"
                }
            ]
        },
        
    const onMenuItemClicked = () => {
        console.log("item clicked");
    }
      
The menubar was declaired as follow inside the <template> tag

Code: Select all

 <template>
    <MenuBar v-if="show" :model="items"/>
    
If someone can help me further, I would be very grateful to him.

Thank you very much.

martindavis
Posts: 4
Joined: 26 Jul 2023, 04:08

26 Jul 2023, 04:12

Hello,
To pass the key option as an input parameter into the onMenuItemClicked function when a menu item is clicked, you can modify the command property of each menu item to call a new function that accepts the key as a parameter and then calls onMenuItemClicked with that parameter.

Here's an example of how you can modify the items array to achieve this:

Code: Select all

clojure
const items = ref([
  { 
    key: 1,
    label: "File",
    items: [
      {
        label: "Open Project",
        icon: "pi pi-fw pi-file-import",
        command: () => onItemClick(1)
      },
      {
        label: "Save Project",
        icon: "pi pi-fw pi-file-export",
        command: () => onItemClick(2)
      }
    ]
  }
]);

const onItemClick = (key) => {
  console.log(`Item with key ${key} clicked`);
  onMenuItemClicked(key);
}

const onMenuItemClicked = (key) => {
  console.log(`Menu item with key ${key} clicked`);
}
In this example, the onItemClick function is called when a menu item is clicked, passing the key of the clicked item as a parameter. onItemClick then calls onMenuItemClicked with the same key parameter. You can modify the onMenuItemClicked function to perform any action you need based on the clicked item's key.

Post Reply

Return to “PrimeVue”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 8 guests