Passing function as prop in Vuejs is not working

500 Views Asked by At

I'm trying to create a custom selector that I ill reuse several times and I want to set a prop to the function it has to trigger when a selection is made. Here is my code (only the relevant parts of it):

Main Selector:

<template>
 <div>
    <select name="selector" >
        <option :key="option" v-for="option in options" @change="selection"> {{option}} </option>
    </select>
 </div>
</template>

<script>
export default {
  name: 'CoffeeSelector',
  props: {
    options: Array,
    selection: Function
  },
}
</script>

The page where I use it:

<template>
  <div>
    <custom-selector :options='types' :selection="coucou"> </custom-selector>
  </div>
</template>

<script>
import CustomSelector from './CustomSelector.vue'

export default {
  name: 'Selectors',
  components: {
    CustomSelector
  },
  methods: {
    coucou(){
      console.log("coucou")
    }
  }
}
</script>

When I do this, nothing happens when I change the selection. Any ideas on why it happens? Thanks in advance

2

There are 2 best solutions below

0
On

You can emit events to the parent component.

<template>
 <div>
    <select name="selector" >
        <option :key="option" v-for="option in options" @change="onOptionChange(option)"> {{option}} </option>
    </select>
 </div>
</template>

<script>
export default {
  name: 'CoffeeSelector',
  props: {
    options: Array
  },
  methods: {
    onOptionChange(option) {
      this.$emit('selection', option);
    }
  }
}
</script>

Then you can listen to those events within the parent component.

<template>
  <div>
    <custom-selector :options='types' v-on:selection="coucou"> </custom-selector>
  </div>
</template>

<script>
import CustomSelector from './CustomSelector.vue'

export default {
  name: 'Selectors',
  components: {
    CustomSelector
  },
  methods: {
    coucou(option){
      console.log("coucou: " + option)
    }
  }
}
</script>
0
On

try moving your @change to the select tag instead

<select name="selector" @change="selection">
  <option :key="option" v-for="option in options"> {{option}} </option>
</select>