Search code examples
vue.jsvue-props

Can we use props to pass variable in vue?


Slall question:

I have a 2 parent components nesting the same child component inside of them. I use props so the parents can tell the child what title to show.

this child component is a photo gallery. It makes a query to the database, download photos and show them up. classic.

I need the parents to tell the child where to get the photos from: Get the photos from All users, for the home page or get only the photos from a specific user for a user's page.

I'm wondering if I can pass this information through a prop. Is that possible? Can we use the info from a prop as a varialble inside of the setup() function? Is there a better way to do this?


Solution

  • Passing objects from one component to a child component is the purpose of props.

    You can pass many items through props. VueJS has the following types built-in:

    • String
    • Number
    • Boolean
    • Array
    • Object
    • Function
    • Promise

    In the V3 VueJS guide it gives the following example of a prop being passed into a component and then being logged to the console inside the setup() method.

    export default {
      props: {
        title: String
      },
      setup(props) {
        console.log(props.title)
      }
    }
    

    However, when using props, you should always mark whether the is required, what its type is and what the default is if it is not required.

    For example:

    export default {
      props: {
        title: String, // This is the type
        required: false, // If the prop is required
        default: () => 'defaultText' // Default needed if required false
      },
      setup(props) {
        console.log(props.title)
      }
    }
    

    It's important to note that when using default, the value must be returned from a function. You cannot pass a default value directly.