There are a few things you can do to pass data in between components, we can use provide/inject
and we also have props
.
In this situation, we’ll talk about props
but if you want to know more about provide/inject
read this article.
The props
(short for properties) are a way to pass data from a parent component to a child component. Props are used to make a component more reusable by allowing the component to accept different data as input.
To use props in a Vue component, you first need to define the props that the component accepts. This is done in the component’s props
option. For example, if a component accepts a prop called “message”, you would define it like this:
props: {
message: {
type: String,
required: true
}
}
This tells Vue that the component expects to receive a prop called “message” that is a string and is required.
Once you’ve defined the props that a component accepts, you can pass data to it when you use the component. This is done by binding the data to the prop in the HTML template. For example, if you have a component called “MyComponent” that accepts a prop called “message”, you can use it like this:
<template>
<div>
<MyComponent :message="someData" />
</div>
</template>
<script>
export default {
data() {
return {
someData: 'Hello World'
}
}
}
</script>
This passes the value of the data property someData
to the message
prop of the MyComponent
component.
In the child component you can use it by referencing to it as this.message
in the template or methods.
<template>
<div>
{{ message }}
</div>
</template>
If you wish to learn more about props
you can read the official Vue documentation here.
I admire your work ethic and how you became a developer with no degree
Pingback: How to use "Provide / Inject" | Vue 3 - Kevin Skayro Blog