Passing Data Between Vue Components
JavaScript, Vue
Components are re-usable Vue instances that better allow you to keep code separated and modular. They are very flexible - child components can be defined and used within parents. This can be a really useful way of preventing repetitive markup.
Single-file components take things to the next level. These keep all component data within a single .vue
file - comprised of a HTML like structure with <template>
(markup), <script>
(JavaScript) and <style>
(CSS) components. This can be really useful for larger projects or projects in which the entire frontend is built in JavaScript.
If you use vue-cli
to spin up a Vue/Webpack project, the project comes with single-file components pre-installed.
This article outlines how to pass data between components in the context of single file components.
Passing Data From Parent Component to Child Component
Import Child in Parent Component
Import the child component so that it can be used in the parent, and declare the component in the <script>
section:
Invoke the Child Component in the Parent
Within the <template>
section of the parent component, call the child component. Prop data is passed as an attribute.
You can pass data inline, or define it within the data()
method of the component.
Note that prepending a colon to the prop attribute indicates that a variable is passed, not a string.
Receiving the Prop Data in the Child
You must declare the prop in the child component <script>
section - you can then use it as a normal Vue-defined variable:
Pass Data from Child to Parent
You can send data from a child to a parent component by means of Vue’s built-in $emit()
method. The first parameter of $emit
is the event that should be listened for in the parent component. The second (optional) parameter is the data value to pass.
Parent:
In this example, the parent listens for the childToParent
event (defined by the $emit
method) and triggers the onChildClick()
method when the event is received. This method in turn sets the fromChild
variable. It also emits an increment
event in a simpler way when the button is clicked, by placing $emit
inline in the template.
In the child component:
This example emits a user-entered string back to the parent component.
comments powered by Disqus