Sam
Sam

Reputation: 1848

vue 3 composition api method is undefined from emit

I have this method updateLocation calling location

setup(props, context) { 
  const updateLocation = (location = null) =>{
    if(location) {
      center.value = location
      context.emit('mapChange', context.location())
    }
  }
  const location = () =>  { return {
    center:center,
  }
}

but I get context.location is not a function. (In 'context.location()', 'context.location' is undefined)

I also tried without context

and also calling the method works from other functions; just not from emit apparently

Upvotes: 1

Views: 1834

Answers (3)

Kapcash
Kapcash

Reputation: 6929

No need to use context if the function is within the same scope. Just give it a different name or it will shadow the variable location.

<script>
export default {
  setup(props, context) { 
    const getLocation = () => {
       return { center: center }
    }

    const updateLocation = (location = null) =>{
      if(location) {
        center.value = location
        context.emit('mapChange', getLocation())
      }
    }
  }
}
</script>

Upvotes: 0

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23510

You can try to rename location argument:

const updateLocation = (loc = null) =>{
if(loc) {
  center.value = loc
  context.emit('mapChange', location())
}

}

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

The context parameter has only 3 properties emit, attrs and slots, you could pass location by props like :

setup(props, context) { 
  const updateLocation = (location = null) =>{
    if(location) {
      center.value = location
      context.emit('mapChange', props.location())
    }
  }
}

Upvotes: 0

Related Questions