2

In a navbar I have to put a list of buttons. While some are links, others should call a method. (e.g. Home should link to /home and Log out should call a function logOut). Because of the large number of items, it is better to have an array with all the buttons/elements that should be rendered

  items: [
    { divider: true },
    { icon: "tasks", text: "Today", link: "/tasks" },
    { icon: "sticky-note", text: "Notes", link: "/notes" },
    { divider: true },
    { heading: "Label" },
    { icon: "code-branch", text: "Branch" },
    { divider: true },
    { icon: "user", text: "Account", link: "/profile" },
    { icon: "cog", text: "Settings" },
    { icon: "sign-out-alt", text: "Log out", action: "logOut" }
  ]

However, I am not sure how to call a method using its name(the last action in the array above). I saw that in js I could use window[item.action]. Is there something similar in Vue? In other words something like @click="methods[item.action]"

2 Answers 2

3

You can create a function to receive the method name and parameters and call the method in this function. You can see in this example

handleFunctionCall(functionName, event) {
        this[functionName](event)
    },
<button v-else-if="item.action" @click="handleFunctionCall(item.action, $event)" >{{item.text}}</button>

Sign up to request clarification or add additional context in comments.

Comments

1

VueJS is still javascript so yes calling the method by its name should work, although I would suggest to use this[*method_name_here*](); to call the function (In the Vue controller I'm not sure if the window would work).

But as you have an action in your list, have you thought of something like this in your view :

<ul>
    <router-link v-for="item in items" to="item.link" @click="item.action"> 
       {{item.text}}
    </router-link>
</ul>

I'm using router-link directly here but you can wrap in <li> tags

Hope this helps !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.