mcd
mcd

Reputation: 726

Vue.js – Passing functions in array as a prop

NavigationBar.vue

The component NavigationBar.vue is used throughout my Vue.js application accepts the following props:

props: {
    title: String,
    actions: Array
}

This is the NavigationBar component:

NavigationBar Component

The component accepts the array to generate the action buttons on the right by using v-for. They are defined in the parent file and are different depending on the place in my application. If you click on a button, the specified function needs to be called.

Members.vue

Members.vue is the parent. Notice the component, actions and functions in there:

<template>
    <div>   
        <NavigationBar title='Members' actions="actionsArray" ></NavigationBar
    </div>  
</template>

<script>
import ...

export default {
  name: 'members',
  components: {
    NavigationBar
  },
  data () {
    return {
        actionsArray: [
            { btnText: 'Create', icon: 'mdi-plus-circle', function: 'createBtnClicked()' },
            { btnText: 'Edit', icon: 'mdi-pencil', function: 'editBtnClicked()' },
        ],
  }
  methods: {
    createBtnClicked() {
        // amazing things will happen here
    },
    editBtnClicked() {
        // it will be even greater when this button is clicked
    },
}

</script>

Problem:

I can't get the functions of the buttons to work as they should. Is passing the function as a prop even the right approach?

I would really appreciate some help! Thanks :)

Upvotes: 2

Views: 1643

Answers (1)

gogo
gogo

Reputation: 1011

You seem to be passing strings and not actual functions.

Try the following:

data () {
    return {
      actionsArray: [
        { btnText: 'Create', icon: 'mdi-plus-circle', function: this.createBtnClicked },
        { btnText: 'Edit', icon: 'mdi-pencil', function: this.editBtnClicked },
      ],
}

Maybe consider declaring explicit prop types to have Vue check values assigned to props have the corect type.

Upvotes: 2

Related Questions