Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use v-for to assign a click event to a v-list-item?

I want to assign a click event to v-list-item using Vue.js v-for. Here is the code:

<v-list-item-group>
  <v-list-item v-for="(item, index) in items" :key="index" @click="item.action">
    <v-list-item-icon>
      <v-icon dark color="#7E6990" v-text="item.icon"></v-icon>
    </v-list-item-icon>
    <v-list-item-title>{{ item.title }}</v-list-item-title>
  </v-list-item>
</v-list-item-group>


<script>
export default {
  data: () => ({
    items: [
      {
        title: "title1",
        icon: "mdi-play-box-multiple",
        action: "logout"
      },
      { title: "title2", 
        icon: "mdi-logout", 
        action: "logout" }
    ]
  }),
  methods: {
    logout() {
        alert('logout!');
    },
  }
}
</script>

I want to assign an action of items to @click. The following will work correctly.

<v-list-item-group class="user-menu">
  <v-list-item v-for="(item, index) in items" :key="index" @click="logout">
    <v-list-item-icon>
      <v-icon dark color="#7E6990" v-text="item.icon"></v-icon>
    </v-list-item-icon>
    <v-list-item-title>{{ item.title }}</v-list-item-title>
  </v-list-item>
</v-list-item-group>

Please tell me how.

like image 555
nayuta shiba Avatar asked Nov 07 '25 18:11

nayuta shiba


2 Answers

I couldn't do it the way I taught. Eventually implemented as follows.

<v-list-item-group>
  <v-list-item v-for="(item, index) in items" :key="index" @click="menuActionClick(item.action)">
    <v-list-item-icon>
      <v-icon dark color="#7E6990" v-text="item.icon"></v-icon>
    </v-list-item-icon>
    <v-list-item-title>{{ item.title }}</v-list-item-title>
  </v-list-item>
</v-list-item-group>

<script>
export default {
  data: () => ({
    items: [
      {
        title: "title1",
        icon: "mdi-play-box-multiple",
        action: "test"
      },
      { title: "title2", 
        icon: "mdi-logout", 
        action: "logout" }
    ]
  }),
  methods: {
    menuActionClick(action) {
      if (action === "test") {
        alert('TEST!!')
      } else if (action === "logout") {
        alert('LOGOUT!!')
      }
    }
  }
}
</script>
like image 129
nayuta shiba Avatar answered Nov 09 '25 10:11

nayuta shiba


In your items, you need to refer action to the logout method, otherwise you are binding the click event to a string:

items: [
  {
    title: "title1",
    icon: "mdi-play-box-multiple",
    action: this.logout          // this.logout instead "logout"
  },
  { title: "title2", 
    icon: "mdi-logout", 
    action: this.logout }
]
like image 33
Psidom Avatar answered Nov 09 '25 10:11

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!