Martin Müsli
Martin Müsli

Reputation: 1159

How to emit a value in composition API

I have a datepicker component, which is included in a form.

How do I emit a value from the datepicker component up to the form component in `Vue3 with the composition API?

The unsuccessful solutions so far where:

  1. Throws: context.emit is not a function
setup(context){
....
 function emitDate(){
   context.emit('chosenDate', datepickerValue.value)
 }
}
  1. Throws: this.$emit is not a function
setup(){
....
  function emitDate(){
    this.$emit('chosenDate', datepickerValue.value)
  }
}

Upvotes: 0

Views: 5022

Answers (2)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23510

You need to pass emit, along props to setup:

setup(props, { emit }) {

function emitDate(){
  emit('chosenDate', datepickerValue.value)
}

or in script setup:

const emit = defineEmits(['chosenDate'])

function emitDate() {
  emit('chosenDate', datepickerValue.value)
}

Upvotes: 2

akuiper
akuiper

Reputation: 215137

The 1st parameter to setup is props. context comes after setup, see setup arguments:

setup(props, context){
....
 function emitDate(){
   context.emit('chosenDate', datepickerValue.value)
 }
}

Or:

setup(props, { emit }){
....
 function emitDate(){
   emit('chosenDate', datepickerValue.value)
 }
}

Upvotes: 1

Related Questions