user4406128
user4406128

Reputation:

How to bind dynamic methods on a v-for

I am trying to dynamically assign methods to elements generated by a template through a v-for. These methods will be assigned according to the value of a given variable. In this case it would be the variable 'btn.method'. Is this possible?


var formButtons = new Vue({
    el: "#formButtons",
    data: {
        buttons: [
            {
                id: "login",
                text: "Login",
                method: "submitForm"
            },
            {
                id: "cancel",
                text: "Cancel",
                method: "clearForm"
            }
        ]
    },
    methods: {
        submitForm: function (event) {
            // Some Code
        },
        clearForm: function (event) {
            // Some Code
        }
    },
    template: `
    <div>
        <div class="form-group"  v-for='btn in buttons'>
            <button
                v-bind:id='btn.id'
                v-on:click='btn.method'
            >
                {{ btn.text }}
            </button>
        </div>
    </div>
    `
});

I tried to pass the method name through a string but it returned the following error, "TypeError: e.apply is not a function.".

I would like each button to have its own method, example:
  - Login button => submitForm method
  - Cancel button => clearForm method

Upvotes: 2

Views: 336

Answers (1)

ittus
ittus

Reputation: 22393

Can you try:

var formButtons = new Vue({
    el: "#formButtons",
    data: {
        buttons: [
            {
                id: "login",
                text: "Login",
                method: "submitForm"
            },
            {
                id: "cancel",
                text: "Cancel",
                method: "clearForm"
            }
        ]
    },
    methods: {
        submitForm: function (event) {
            // Some Code
        },
        clearForm: function (event) {
            // Some Code
        },
        onClick(methodName) {
          this[methodName]()
        }
    },
    template: `
    <div>
        <div class="form-group"  v-for='btn in buttons'>
            <button
                v-bind:id='btn.id'
                v-on:click='onClick(btn.method)'
            >
                {{ btn.text }}
            </button>
        </div>
    </div>
    `
});

Upvotes: 1

Related Questions