Unable to pass function as prop to child component in Vue 3

Viewed 15

I am trying to pass a method down to a child component in Vue 3.

Parent Component

<template>
  <div class="grid-item">                           
     <SiteCmpnt :sID = "'Z'" :SiteToEdit="EditSite"></SiteCmpnt>
  </div>
</template>
setup() {
  const EditSite = (siteID) => {
    console.log("I'm ready to edit site: ", siteID)
  }
  return {EditSite}   
} 

Child Component

<template>
  <div  class="sbs2">
    <Icon name="edit" @click="EditSite(sID)"/> 
  </div>
</template>

<script>
  props: {
    sID:String,
    SiteToEdit: Function
  },
  setup(props){
    const EditSite = (siteID) => {
      console.log("Edit site: ", siteID)
      props.SiteToEdit(siteID);
  }
  return {EditSite}
}

When I click on the Icon I get "props.SiteToEdit is not a function".

I also Tried

 <div  class="sbs2">
   <Icon name="edit" @click="SiteToEdit(sID)"/> 
 </div>    

But got the same response

1 Answers

Maybe I misunderstood what you wanted to do, but if you want to click on the parent function you should use the emit method :)

<template>
          <div class="grid-item">                           
             <SiteCmpnt :sID = "'Z'" @size-to-edit="EditSite"></SiteCmpnt>
          </div>
        </template>
        setup() {
          const EditSite = (siteID) => {
            console.log("I'm ready to edit site: ", siteID)
          }
          return {EditSite}   
     } 
</template>

Child component:

<template>
  <div  class="sbs2">
    <Icon name="edit" @click="$emit("sizeToEdit")"/> 
  </div>
</template>

<script>
  props: {
    sID:String,
  },
}

https://vuejs.org/guide/components/events.html

Related