Bilal Hussain
Bilal Hussain

Reputation: 95

How to access props passed inside a setup function for Vuejs (Composition API)

When I use props to pass an object into the child component, I am unable to use the props inside the setup function (Composition API). I am trying to use the props to run a query from the firebase using the displayName property of the user instead of using 'Abe'. I am new to Vue, please help me out!

<template>
  <div v-if="user">
      <Process :user="user"/>
  </div>
  <div v-else>
      <h1>Loading user</h1>
  </div>
</template>

<script>
import Process from '../views/Process.vue'
import getUser from '@/composables/getUser'
export default {
    components: { Process },
    setup(){
        const { user } = getUser();
    
        return {user}
    }

}
</script>

Using user in the setup function gives an undefined error but using it at top of the template returns the correct object.

<template>
  <p>Process Payroll</p>
  <h1>{{ user.displayName }} </h1>
  <h1>{{ docs }} </h1>
</template>

<script>
// import getUser from '@/composables/getUser'
import { ref, onMounted, watch } from 'vue'
import { projectFirestore, projectAuth } from '@/firebase/config'
import { useRouter, useRoute } from 'vue-router'

export default {
    props: ['user'],
    setup() {
    // const { user } = getUser();

    // watch(()=> user, () => returnUser())

    const lastName = ref("");
    const firstName = ref("");
    const docs = ref("");

    const returnUser = async () => {
        const res = await projectFirestore
            .collection("users")
            .where("displayName", "==", "Abe") // Case sensitive
            .get();

        const lastNameList = res.docs.map(d => `Abe ${d.data().lastName}`)
        console.log(lastNameList)
        console.log(user)
        console.log(user.displayName)
        docs.value = lastNameList;
    }

    onMounted(returnUser)

    return { docs, returnUser};
  },
}
</script>

Upvotes: 2

Views: 3089

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

Pass props to setup function:

setup(props) {
....

Upvotes: 4

Related Questions