Sameer
Sameer

Reputation: 91

How to assign same event listener to dynamically created buttons in Vue.js and pass object's value to it as parameter?

I'm trying to create buttons dynamically whose names are fetched from keys of an Object. And I need to pass the corresponding value to the method to get my code work. How do you do both of these tasks?


<template>
  <v-app>
    <router-view></router-view>
    <v-app-bar app dense id="abc" dark>
      <v-icon>note_add</v-icon>
      <v-toolbar-title>Title</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-btn
        v-for="(value, key) in button_redirect_to"
        :key="key"
        @click="render_comp()"
      >{{ key }}</v-btn>
      <v-btn depressed fab small>
        <v-icon>notifications</v-icon>
      </v-btn>
    </v-app-bar>
  </v-app>
</template>

<script>
export default {
  name: "Navbar",
  data() {
    return {
      button_redirect_to: {
        Projects: "/projects",
        Requests: "/requests",
        Reports: "/reports",
        Resources: "/resources",
        temp: "/temp"
      },
      pers_actions: ["Profile", "LogOut"]
    };
  },
  methods: {
    render_comp() {
      this.$router.push();
    }
  }
};
</script>




Upvotes: 0

Views: 181

Answers (2)

kaitrenbath
kaitrenbath

Reputation: 201

Pass the value variable from the for loop (which in the first case will be "/projects") as an argument of @click="render_comp(value)" handler so it can be used inside the function.

<v-btn
    v-for="(value, key) in button_redirect_to"
    :key="key"
    @click="render_comp(value)"
>
    {{ key }}
</v-btn>

render_comp will then have access to it so it can be passed into this.$router.push(), making the function this.$router.push("/projects").

methods: {
    render_comp(value) {
        this.$router.push(value);
    }
}

Hope this helps.

Upvotes: 0

Decade Moon
Decade Moon

Reputation: 34286

In your for-loop, value is the route and key is the button label. Just pass the route (value) as an argument:

@click="render_comp(value)"
methods: {
  render_comp(to) {
    this.$router.push(to);
  }
}

Upvotes: 1

Related Questions