• 18-19 College Green, Dublin 2
  • 01 685 9088
  • info@cunninghamwebsolutions.com
  • cunninghamwebsolutions
    Cunningham Web Solutions
    • Home
    • About Us
    • Our Services
      • Web Design
      • Digital Marketing
      • SEO Services
      • E-commerce Websites
      • Website Redevelopment
      • Social Media Services
    • Digital Marketing
      • Adwords
      • Social Media Services
      • Email Marketing
      • Display Advertising
      • Remarketing
    • Portfolio
    • FAQ’s
    • Blog
    • Contact Us
    MENU CLOSE back  

    How To Pass Data Between Components In Vue.js

    You are here:
    1. Home
    2. Web Design
    3. How To Pass Data Between Components In Vue.js
    Thumbnail for 24335
    Smashing Editorial

    How To Pass Data Between Components In Vue.js

    How To Pass Data Between Components In Vue.js

    Matt Maribojoc

    2020-01-22T13:00:00+00:00
    2020-01-23T12:35:21+00:00

    Sharing data across components is one of the core functionalities of VueJS. It allows you to design a more modular project, control data scopes, and create a natural flow of data across your app.

    Unless you’re creating your entire Vue app in one component (which wouldn’t make any sense), you’re going to encounter situations where you need to share data between components.

    By the end of this tutorial, you will know three ways to get this done.

    • Using props to share data from parent to child,
    • Emitting custom events to share data from child to parent,
    • Using Vuex to create an app-level shared state.

    Okay — let’s get right into it!

    Building An App With Nuxt

    With Spotify, your friends can check out what you’re jamming to. What if the rest of the Internet could experience your algo-rhythm, too? Learn how to compose your own app to share what you’re listening to on Spotify using Vue.js and Nuxt. →

    1. Using Props To Share Data From Parent To Child

    VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we’re passing data from a parent to a child component!

    For example, let’s say we’re working on a user profile page and want to have a child component accept a username prop. We’ll need two components.

    1. The child component accepting the prop, let’s call this AccountInfo.vue.
    2. The parent component passing the prop, let’s call this ProfilePage.vue.

    Inside AccountInfo.vue, we can declare the props it accepts using the props option. So, inside the component options, let’s make it look like the following.

    // AccountInfo.vue
    
    <template>
     <div id='account-info'>
       {{username}}
     </div>
    </template>
     
    <script>
    export default {
     props: ['username']
    }
    </script>

    Then, to actually pass the data from the parent (ProfilePage.vue), we pass it like a custom attribute.

    // ProfilePage.vue
     
    <account-info username='matt' />

    Now if we load our page, we can see that our AccountInfo component properly renders the value passed in by its parent.

    As when working with other VueJS directives, we can use v-bind to dynamically pass props. For example, let’s say we want to set the username prop to be equal to a variable. We can accomplish this by using shorthand for the v-bind directive (or just : for short). The code would look a little like this:

    <template>
     <div>
       <account-info :username="user.username" />
     </div>
    </template>
     
    <script>
    import AccountInfo from "@/components/AccountInfo.vue";
     
    export default {
     components: {
       AccountInfo
     },
     data() {
       return {
         user: {
           username: 'matt'
         }
       }
     }
    }
    </script>

    This means that we can change our data and have any child props using that value will also update.

    Tip: Always Verify Your Props

    If you’re looking to write clearer Vue code, an important technique is to verify your props. In short, this means that you need to specify the requirements for your prop (i.e. type, format, and so on). If one of these requirements is not met (e.g. if the prop is passed an incorrect type), Vue will print out a warning.

    Let’s say we want our username prop to only accept Strings. We would have to modify our props object to look like this:

    export default {
     props: {
       username: String
     }
    }

    Verifying props is essential when working in large-scale Vue apps or when designing plugins. It helps ensure that everyone is on the same page and use props the way that they were intended.

    For a full list of the verifications we can include on props, I’d definitely recommend checking out the official documentation for an in-depth review.

    Tip: Follow Prop Naming Conventions

    According to the VueJS style guide, the best way to name your props is by using camelCase when declaring them in your script and kebab-case when referencing them in template code.

    The reasoning behind this is actually quite simple. In Javascript, camelCase is the standard naming convention and in HTML, it’s kebab-case.

    So, Vue recommends that we stick to the norms of each language. Thankfully, Vue is able to automatically convert between the two styles so there’s no additional setup for developers.

    // GOOD
    <account-info :my-username="user.username" />
    props: {
       myUsername: String
    }
     
    // BAD
    <account-info :myUsername="user.username" />
    props: {
       "my-username": String
    }

    2. Emitting Events To Share Data From Child To Parent

    Now that we have data passing down the hierarchy, let’s pass it the other way: from a child component to a parent. We can’t use props, but we can use custom events and listeners.

    Every Vue instance can call a .$emit(eventName) method that triggers an event. Then, we can listen for this event in the same way as any other, using the v-on directive.

    Creating a Custom Event

    Let’s build on our user profile example by adding a button that changes the username. Inside our child component (AccountInfo.vue), let’s create the button.

    Then, when this button is clicked, we’ll emit an event called changeUsername.

    <template>
     <div id='account-info'>
       <button @click='changeUsername()'>Change Username</button>
       {{username}}
     </div>
    </template>
     
    <script>
    export default {
     props: {
       username: String
     },
     methods: {
       changeUsername() {
         this.$emit('changeUsername')
       }
     }
    }
    </script>

    Inside the parent, we handle this event and change the user.username variable. Like we were discussing earlier, we can listen to events using the v-on directive or “@” for short.

    <template>
     <div>
       <account-info :username="user.username" @changeUsername="user.username = 'new name'"/>
     </div>
    </template>

    Let’s try it out. You should see that when you click the button, the username changes to “new name”.

    Tip: Custom Events Can Accept Arguments

    The most common use case for passing arguments to your events is when you want a child component to be able to set a specific value for its prop. You never want to directly edit the value of a prop from the component itself.

    However, luckily we can use pass arguments with our custom events to make the parent component change values.

    Let’s say we want to modify the changeUsername event so that we can pass it a value.

    The $emit method takes an optional second parameter for arguments. So all we do is add our new username value after the name of our event.

    this.$emit('changeUsername', 'mattmaribojoc')

    Then, in our parent component, we can either access these values inline by using a special $event variable, or we can write a handler method that takes a parameter.

    <account-info :username="user.username" @changeUsername="user.username = $event"/>
     
    OR 
     
    <account-info :username="user.username" @changeUsername="changeUsername($event)"/>
     
    export default {
    ...
    methods: {
       changeUsername (username) {
         this.user.username = username;
       }
    }
    }

    3. Using Vuex To Create An Application-Level Shared State

    Okay — we know how to share data between parents/children, but what about other components? Do we have to create an extremely complex hierarchy system if we want to pass data?

    Thankfully not. The wonderful Vuex state management library has been simplifying developers’ lives for years. In short, it creates a centralized data store that is accessible by all components.

    In the methods we used previously (props / emitting events), each component has its own data state that we then share between components. However, Vuex lets us extract all the shared data into a single state that each component can access easily. This shared state is called a store.

    Let’s try it out.

    Because Vuex is separate from the core code of Vue, we’ll first have to install and import it into our project. First, we’ll have to run npm install vuex --save inside our project CLI.

    Then, create a src/store folder with an index.js file that contains the following code.

    // store/index.js
     
    import Vue from "vue";
    import Vuex from "vuex";
     
    Vue.use(Vuex);
     
    export default new Vuex.Store({
     state: {},
     getters: {},
     mutations: {},
     actions: {}
    });

    To include this in our root Vue instance, we have to import our store/index.js file and pass it in our Vue constructor.

    // main.js
     
    import store from "./store";
     
    new Vue({
      store,
      ...

    Accessing Vue Store Inside Components

    Since we added our Vuex store onto our root Vue instance, it gets injected into all of the root’s children. If we want to access the store from a component, we can via this.$store.

    Now, let’s dive into the specifics of each of the four parts of a Vuec store.

    1. State

    The Vuex state is an object that contains application-level data. All Vue instances will be able to access this data.

    For our store, let’s create a user object that stores some more user profile data.

    export default new Vuex.Store({
     state: {
       user: {
         username: 'matt',
         fullName: 'Matt Maribojoc'
       }
     },
     getters: {},
     mutations: {},
     actions: {}
    });

    We can access this data inside any instance component like this.

    mounted () {
       console.log(this.$store.state.user.username);
    },

    2. Getters

    We use Vuex getters to return a modified value of state data. A good way to think of getters is to treat them like computed properties. For example, getters, like computed properties, cache their results and only re-evaluate when a dependency is modified.

    Building onto our earlier store, let’s say we want to make a method that returns a user’s first name based off the full name attribute.

    getters: {
       firstName: state => {
         return state.user.fullName.split(' ')[0]
       }
     }

    Vuex getter properties are available to components on the store.getters object.

    mounted () {
       console.log(this.$store.getters.firstName);
    }
    Tip: Know the Default Getter Arguments

    By default, Vuex getters accept two arguments.

    1. state — the state object for our application;
    2. getters — the store.getters object, meaning that we can call other getters in our store.

    Every getter you declare will require the first state argument. And depending on how you design your code, your getters can reference each other using the second ‘getters’ argument.

    Let’s make a last name getter that simply removes our first name value from our full name state property. This example would require both the state and getters objects.

    lastName (state, getters) {
         return state.user.fullName.replace(getters.firstName, '');
    }
    Tip: Pass Custom Arguments to Vuex Getters

    Another cool feature of getters is that we can pass them custom arguments by making our getter return a method.

    prefixedName: (state, getters) => (prefix) => {
         return prefix + getters.lastName;
    }
     
    // in our component
    console.log(this.$store.getters.prefixedName("Mr."));

    3. Mutations

    Mutations are the only way to properly change the value of the state object. An important detail to note is that mutations must be synchronous.

    Like getters, mutations always accept the Vuex state property as their first argument. They also accept a custom argument — called a payload — as the second argument.

    For example, let’s make a mutation to change a user’s name to a specific value.

    mutations: {
       changeName (state, payload) {
         state.user.fullName = payload
       }
    },

    Then, we can call this method from our component using the store.commit method, with our payload as the second argument.

    this.$store.commit("changeName", "New Name");

    More often than not, you are going to want your payload to be an object. Not only does this mean that you can pass several arguments to a mutation, but also, it makes your code more readable because of the property names in your object.

    changeName (state, payload) {
         state.user.fullName = payload.newName
    }

    There are two different ways to call mutations with a payload.

    1. You can have the mutation type as the first argument and the payload as the second.
    2. You can declare pass a single object, with one property for the type and another for the payload.
    this.$store.commit("changeName", {
           newName: "New Name 1",
    });
     
         // or
     
     this.$store.commit({
           type: "changeName",
           newName: "New Name 2"
    });

    There isn’t a real difference between how the two work so it’s totally up to personal preference. Remember that it’s always best to be consistent throughout your entire project, so whichever one you choose, stick with it!

    4. Actions

    In Vuex, actions are fairly similar to mutations because we use them to change the state. However, actions don’t change the values themselves. Instead, actions commit mutations.

    Also, while Vuex mutations have to be synchronous, actions do not. Using actions, we can call a mutation after an API call, for example.

    Whereas most of the Vuex handlers we’ve seen accept state as their main parameter, actions accept a context object. This context object allows us to access the properties in our Vuex store (e.g. state, commit, getters).

    Here’s an example of a Vuex action that waits two seconds and then commits the changeName mutation.

    actions: {
       changeName (context, payload) {
         setTimeout(() => {
           context.commit("changeName", payload);
         }, 2000);
       }
    }

    Inside our components, we use the store.dispatch method in order to run our function. We pass arguments just like we did with mutations. We declare the type and we pass any custom arguments in the second argument.

    this.$store.dispatch("changeName", {
          newName: "New Name from Action"
    });

    Wrapping Up

    Now, you should know three different ways to share data across components in VueJS: props, custom events, and a Vuex store.

    I hope this tutorial helped give you some more insight into some different Vue methods and best practices. Let me know how you’ve implemented them into your projects!

    Further Reading

    If you’re interested in going even deeper into the technical side/capabilities of each technique, here are some great places to start.

    • Vuex Official Guide website
    • VueJS Docs for Props and Custom Events
    • “WTF Is Vuex? A Beginner’s Guide To Vue’s Application Data Store,” Anthony Gore, Vue.js Developers

    (dm, yk, il)

    From our sponsors: How To Pass Data Between Components In Vue.js

    Posted on 23rd January 2020Web Design
    FacebookshareTwittertweetGoogle+share

    Related posts

    Archived
    22nd March 2023
    Archived
    18th March 2023
    Archived
    20th January 2023
    Thumbnail for 25788
    Handling Continuous Integration And Delivery With GitHub Actions
    19th October 2020
    Thumbnail for 25778
    A Monthly Update With New Guides And Community Resources
    19th October 2020
    Thumbnail for 25781
    Supercharge Testing React Applications With Wallaby.js
    19th October 2020
    Latest News
    • Archived
      22nd March 2023
    • Archived
      18th March 2023
    • Archived
      20th January 2023
    • 20201019 ML Brief
      19th October 2020
    • Thumbnail for 25788
      Handling Continuous Integration And Delivery With GitHub Actions
      19th October 2020
    • Thumbnail for 25786
      The Future of CX with Larry Ellison
      19th October 2020
    News Categories
    • Digital Marketing
    • Web Design

    Our services

    Website Design
    Website Design

    A website is an important part of any business. Professional website development is an essential element of a successful online business.

    We provide website design services for every type of website imaginable. We supply brochure websites, E-commerce websites, bespoke website design, custom website development and a range of website applications. We love developing websites, come and talk to us about your project and we will tailor make a solution to match your requirements.

    You can contact us by phone, email or send us a request through our online form and we can give you a call back.

    More Information

    Digital Marketing
    Digital Marketing

    Our digital marketeers have years of experience in developing and excuting digital marketing strategies. We can help you promote your business online with the most effective methods to achieve the greatest return for your marketing budget. We offer a full service with includes the following:

    1. Social Media Marketing

    2. Email & Newsletter Advertising

    3. PPC - Pay Per Click

    4. A range of other methods are available

    More Information

    SEO
    SEO Services

    SEO is an essential part of owning an online property. The higher up the search engines that your website appears, the more visitors you will have and therefore the greater the potential for more business and increased profits.

    We offer a range of SEO services and packages. Our packages are very popular due to the expanse of on-page and off-page SEO services that they cover. Contact us to discuss your website and the SEO services that would best suit to increase your websites ranking.

    More Information

    E-commerce
    E-commerce Websites

    E-commerce is a rapidly growing area with sales online increasing year on year. A professional E-commerce store online is essential to increase sales and is a reflection of your business to potential customers. We provide professional E-commerce websites custom built to meet our clients requirements.

    Starting to sell online can be a daunting task and we are here to make that journey as smooth as possible. When you work with Cunningham Web Solutions on your E-commerce website, you will benefit from the experience of our team and every detail from the website design to stock management is carefully planned and designed with you in mind.

    More Information

    Social Media Services
    Social Media Services

    Social Media is becoming an increasingly effective method of marketing online. The opportunities that social media marketing can offer are endless and when managed correctly can bring great benefits to every business.

    Social Media Marketing is a low cost form of advertising that continues to bring a very good ROI for our clients. In conjuction with excellent website development and SEO, social media marketing should be an essential part of every digital marketing strategy.

    We offer Social Media Management packages and we also offer Social Media Training to individuals and to companies. Contact us to find out more.

    More Information

    Cunningham Web Solutions
    © Copyright 2025 | Cunningham Web Solutions
    • Home
    • Our Services
    • FAQ's
    • Account Services
    • Privacy Policy
    • Contact Us