Props
If you are from the React world, you will be very familiar with props. Vue offers similar functionality with their prop system.
If not, here’s a short explanation of what props are: props are pieces of data that you pass down to child components.
Props fulfill the first part of a two-way communication system between components.
Declaring Props
In the child component, we need to declare props and assign a type:
<template> <main> <h1> This is a header </h1> //render prop {{ props.subTitle }} </main></template><script setup>import { defineProps } from 'vue';//Define prop, prop name, and typeconst props = defineProps({ subTitle: String})</script>
Passing Props
Passing a prop requires no declaration in the script. You create the prop name within the template and pass a value.
<template> <main> //Component added, prop name declared, value passed to component <HeaderComponent subTitle="Welcome to Vue Reference" /> </main></template>
In this example, we are calling a component called HeaderComponent. Then we declare a prop called subTitle and pass in a string value.
Reactive Props
We can also make props dynamic:
<template> <main> //Component added, prop name declared, value passed to component <HeaderComponent :subTitle="subTitleValue" /> </main></template><script setup> import { ref } from "vue"; let subTitleValue = ref("Welcome to Vue Reference");</script>
We use the v-bind directive (in this case the colon shorthand), and bind the variable subTitleValue to the prop we are passing. We also make sure to use "ref" to tell Vue that the property is reactive and needs to trigger a rerender when changed.
Passing Expressions
We can also create expressions within a prop:
<template> <main> //Component added, prop name declared, value passed to component <HeaderComponent :subTitle="subTitleValue 'by' author" /> </main></template><script setup> let subTitleValue = "Welcome to Vue Reference"; let author = "Brian Driscoll"</script>
And you can pass booleans, object, arrays, and any other type value into a prop.