[Vuejs]-Vue.js 2.x Passing function to component

5πŸ‘

βœ…

To pass a function as a prop to the component, you need to strip off the trailing parentheses of the function name. Otherwise, Vue will evaluate the function. For example:

<geography-field
  label="Pa&iacute;s"
  :_default="selectedCountry"
  placeholder="Choose a country"
  name="country"
  :collection="countries"
  :onchange="selectCountry" // strip off the parentheses
></geography-field>

But, I would also suggest you use $emit instead of passing a function. You can do that like so:

The component definition:

<template>
  <fieldset class="form-group col-md">
    <label :for="name" class="control-label" v-html="label"></label>
    <select class="form-control" :name="name" :id="name" :model="_default" :disabled="disabled" @change="onchange">
      <option :value="0" v-html="placeholder"></option>
      <option v-for="object in collection" :value="object.id">{{ object.name }}</option>
    </select>
  </fieldset>
</template>

<script>
module.exports = {
  props: {
    label: { type: String, default: 'Options' },
    _default: { type: Number, default: 0 },
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: 'Choose an option' },
    name: { type: String, required: true },
    collection: { type: Array, required: true }
  },
  methods: {
    onchange() {
      this.$emit("onchange"); 
    }
  }
}
</script>

The component tag in the parent scope:

<geography-field
  label="Pa&iacute;s"
  :_default="selectedCountry"
  placeholder="Choose a country"
  name="country"
  :collection="countries"
  @onchange="selectCountry" // use @
></geography-field>
πŸ‘€wang

1πŸ‘

e.g.
:onchange="selectCountry"

Don’t put () when you pass the function. It will trigger the function execution and whatever the function return will be pass into onchange.

πŸ‘€Jacob Goh

Leave a comment