/vuejs, vue, component, props

VueJS pass data and methods to child component

I couldn't find a clear explanation of how to pass both data and methods from parent component to a child component in VueJS.
Remember, there's always more that one way of doing almost anything. Below is just one of those ways. More detailed, albeint no so clear, explanation and all the other ways of passing props can be found in official documentation.

Parent component

Let's assume you have a child component called Childcomponent. Passing properties down to the child component is as simple as adding :prop="value" multiple times.
You can pass a single value, array :ids="[324, 12, 434]" or an object :name="{ first: 'AAA', last: 'BBB' }". What was a very nice surprise for me, you can pass methods in exactly the same way. Then you can run methods from within your child component that are defined in your parent component. Super handy.

<div id="components-demo">
  <Childcomponent
    :first-name="firstName"
    :status="whatever.path.status"
    :some-method="someMethod"
    :submit="submitForm" />
</div>


<script>
import Childcomponent from '~/components/Childcomponent.vue'

export default {
  components: {
    Childcomponent
  },
  data() {
    return {
      firstName: 'whatever',
      whatever: {
        path: {
          status: true
        }
      }
    }
  },
  methods: {
    someMethod() {
      // do something
    },
    submitForm() {
      // do something else
    }
  }
}
</script>

Child component

In child component, you need to define passed properties. Notice, in parent component prop names should use kebab case first-name, but when defining them in child component, use camel case firstName. Also methods passed from parent need to be defined in the child as a type Function.
Then, you can use your data and methods (from parent) in the child component just as you'd do it normally.

<template>
  <div>
    <div class="col">
      <img :src="loadImage(status)" alt="alt text">
    </div>
    <button
      class="btn btn-sm btn-outline-light"
      @click="submit">
      Submit
    </button>
  </div>
</template>

<script>
export default {
  name: 'Childcomponent',
  props: {
    firstName: {
    type: String,
      default() {
        return 'My name'
      }
    },
    status: {
      type: Boolean,
      default() {
        return false
      }
    },
    loadImage: {
      type: Function,
      default() {
        return {}
      }
    },
    submit: {
      type: Function,
      default() {
        return {}
      }
    }
  }
}
</script>