devman
devman

Reputation: 701

Vue: passing onclick-method name via props

I want to create components in a loop, passing properties to the child by name.

so: <card-base v-for="(card, i) in cards" :key="i" :heading="card.heading" :width="card.width" class="dashboard-card" :cardHeaderButtons="[{icon: 'minimize', fn: 'minimizeDashboardCard'}]">

in my (child!) component i have defined the minimizeDashboardCard method, and

                <v-btn icon flat class="header-button" v-for="(button, i) in cardHeaderButtons"
                       :key="i"
                       v-if="$vuetify.breakpoint.lgAndUp"
                       color="white"
                       @click.capture.stop="button.fn"
                >
                    <v-icon>
                        {{ button.icon }}
                    </v-icon>
                </v-btn>

the {{ button.icon }} works. but the fn doesn't

Uncaught TypeError: button.fn is not a function
    at !click (CardBase.vue?ac7a:32)
    at invoker (vue.esm.js?efeb:2027)
    at HTMLButtonElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1826)

i also tried with this[button.fn], but that doesn't work either.

the solution is probably super easy, but i don't see it right now. how can i pass the method NAME? (like for minimize, i want to have methods defined once in that card component and just have to pass the name to reuse it.)

thanks :)

Upvotes: 0

Views: 3132

Answers (3)

Husam Elbashir
Husam Elbashir

Reputation: 7187

How about using a helper method ..

methods: {
  ...
  call(methodName) {
    this[methodName]()
  }
}

Then you can do this in your template ..

 <v-btn icon flat class="header-button" v-for="(button, i) in cardHeaderButtons"
                       :key="i"
                       v-if="$vuetify.breakpoint.lgAndUp"
                       color="white"
                       @click.capture.stop="call(button.fn)"
>

Upvotes: 4

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

pass button as parameter to a method like :

   @click.capture.stop="callBtn(button)"

in your methods :

  methods:{
      callBtn(button){
       button.fn();
       }
    ...  
     }

Upvotes: 1

Efrat Levitan
Efrat Levitan

Reputation: 5622

maybe try @click.capture.stop="eval(button.fn).call()"

https://www.w3schools.com/js/js_function_call.asp

Upvotes: 1

Related Questions