create account

Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js by aafeng

View this thread on: hive.blogpeakd.comecency.com
· @aafeng ·
$35.86
Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js
![](https://cdn.steemitimages.com/DQmSnFb8dojCSjhpeXagQowTaqY11zrwfaxbXJsffKyYY6T/image.png)

## Repository

Vue.js: https://github.com/vuejs/vue

## What Will I Learn?

* How to pass data between parent and child components
* How to manage states by Vuex
* How to persist data in Vue.js application

## Requirements

* A Node.js environment (Ubuntu 18 + Node.js is used in this tutorial)
* Basic HTML/CSS/Javascript knowledge

## Difficulty

Basic level

## Tutorial contents

In last tutorial, dynamic route and event handling has been discussed. A few components have been added. Now it is the time to think about how to pass information between components. The most basic way of passing data between components will be discussed first, e.g. using parameters and events between parent and child components. Then the limitations will be discussed and Vuex will be introduced to manage the states within the application. Furthermore, vuex-persist is discussed to have data stored in the local storage.

### Passing data between parent and child components

#### Add three components

To demonstrate how to pass data between parent and child components, three components will be added: 
* Settings is the parent component which will handle all events happening in the children components. 
* PostSettings is a child component which will handle all settings related to posts/comments.
* ActivitySettings is a child component which will handle all activities settings.

First, add components/PostSettings.vue with the following content:

    <template>
      <div>
        <h4>Post Settings</h4>
        <label for="number">Default number of posts/comments</label>
        <input name="number">
      </div>
    </template>

    <script>
    export default {
      // Name of this component
      name: 'PostSettings'
    }
    </script>

    <style scoped>
    </style>

Second, add components/ActivitySettings.vue with the following content:

    <template>
      <div>
        <h4>Activity Settings</h4>
      </div>
    </template>

    <script>

    export default {
      name: 'ActivitySettings'
    }
    </script>

    <style scoped>
    </style>

Last, add components/Settings.vue with the following content:

    <template>
      <div>
        <ActivitySettings></ActivitySettings>
        <hr/>
        <PostSettings></PostSettings>
      </div>
    </template>

    <script>
    import ActivitySettings from './ActivitySettings'
    import PostSettings from './PostSettings'

    export default {
      // Name of this component
      name: 'Settings',
      components: {ActivitySettings, PostSettings}
    }
    </script>

    <style scoped>
    </style>

The application should look like:

![](https://cdn.steemitimages.com/DQmVhis22JXyGR1JtnLUYbUD4ggja93tHfvf5rVnePr9zMK/image.png)

#### Passing data from parent to child component

To pass data from parent to child component, firstly, some properties need to be defined in the child component, e.g. ‘operations’ is added to ActivitySettings.vue:

    props: ['operations']

To display if the data is received properly, add this line in the template:

    {{operations}}

More complex processing logic can be added in ActivitySettings component. But for now, that is enough to demonstrate how the child component receive the data passed from parent component.

Now, update parent component, e.g. add this line into parent component’s template:

    <ActivitySettings operations="vote,transfer,comment,reward"></ActivitySettings>

In the above code, ‘operations’ is the property name defined in the child component. The application should look like:

![](https://cdn.steemitimages.com/DQmZu9hjmVAViB369p8jdMBom1Vhv9LUvziJfsmCLGAw3wR/image.png)
 
#### Passing data from child to parent component

To demonstrate how to emit data via event from child to parent component, first add ‘changed’ method to PostSettings component:

    // This event handler will emit an event with data to parent component
    changed: function (event) {
      this.$emit('default_number_changed', event.target.value)
    }

In the above code, ‘default_number_changed’ is the event name and ‘event.target.value’ is the value to be passed to parent component.

Also, the event handler must bind to the input field, e.g.

    <input @input="changed" name="number">

By this way, whenever the user provides any input, the ‘default_number_changed’ event will be emitted to parent component. 

In parent component, e.g. Settings.vue, the following code needs to be added to receive the event:

    <PostSettings @default_number_changed="handleChange"></PostSettings>

Also, add some processing logic:

    methods: {
      handleChange: function (number) {
        console.log('Number is changed to: ' + number)
      }
    }

Open the developer tool in the browser, the output should be seen as shown below:

![](https://cdn.steemitimages.com/DQmZ6bDj2x4bpPwDNA3KHKEn4uwXRwYSuYm1P4q5nmVy9bU/image.png)

### State management via Vuex

As discussed in previous section, component properties and events can be used to pass information between parent and children components. However, when the application is getting bigger, it is very common to share data among components which do not have direct relationships. For example, in the demo application, in ‘Settings’ component,  some users’ preferences will be stored there and these preferences need to be accessible by other components, e.g. Posts, Comments etc. The Settings component does not have a parent-child relationship with Posts and Comments. In this case, Vuex is a perfect choice to share data among these components. 

#### Install Vuex

To use Vuex, first, run the following command to install vuex package and get it added into package.json

    npm install --save vuex

#### Add Vuex store

Then create file: store/index.js with the following content:

    import Vuex from 'vuex'
    import Vue from 'vue'

    // Declare that Vuex will be used to manage states
    Vue.use(Vuex)

    export default new Vuex.Store(
      // Declare the states need to be managed
      state: {
        default_number_of_posts: 10
      }
    })

In the above code, after importing Vuex, ‘Vue.use(Vuex)’ must be used to let Vue know that Vuex is the state manager now. Then any states can be added to Vuex store and they will be available to other Vue components. In here, for demo purpose, only one state, e.g. ‘default_number_of_posts’ is used. 

The state can be modified and retrieved by using mutations and getters, e.g. 

    mutations: {
      change (state, number) {
        state.default_number_of_posts = number
      }
    },
    getters: {
      default_number_of_posts: state => state.default_number_of_posts
    }

#### Update main.js

Then ‘main.js’ needs to be updated to make a reference to the Vuex store. First import the file:

    import store from './store'    

And update the main Vue component to:

    new Vue({
      el: '#app',
      store, // declare the 'store' will be used for state management
      router, // default router
      components: { App }, // the main component
      template: '<App/>' // This will load the template defined in App.vue
    })

#### Access state from other components

Now, it is ready to share the state, e.g. ‘default_number_of_posts’ among components. First open components/Comments.vue and make the following change:

    <template>
      <div>
        Default number of posts/comments: 
        **{{ $store.getters.default_number_of_posts }}**
      </div>
    </template>

The value of ‘default_number_of_posts’ will be displayed in Comments component. 

Similarly, the default number of posts being loaded in Posts, e.g. change:

    steem.api.getDiscussionsByAuthorBeforeDate(this.username, null, new Date().toISOString().split('.')[0], 10, function (err, result) {

to:

    steem.api.getDiscussionsByAuthorBeforeDate(this.username, null, new Date().toISOString().split('.')[0], this.$store.getters.default_number_of_posts, function (err, result) {

#### Change state value

To store the value of state, ‘changed’ method in PostSettings component need to be updated:

    methods: {
      // changed event handler will send the new value to Vuex store
      changed: function (event) {
        this.$store.commit('change', event.target.value)
      }
    }

So, it is ready to test now. Change the default number of posts to ‘20’ and navigate to ‘Posts’ tab, the behaviour of Posts component will be changed!

### Data persistent in Vue.js

In the previous section, Vuex has been discussed to share data among components. But, what will happen if the browser is closed, or the server is restarted? All data being saved to state by Vuex will be lost! The reasons is because that state management is a mechanism to store application’s states **within the application’s lifecycle**.  If any information needs to be saved in the storage, some extra work needs to be done. In this case, vuex-persist can be used to store states to a storage, e.g. local storage within the browsers.

#### Install vuex-persist

First run this command to install ‘vuex-persist’ package:

    npm install vuex-persist

#### Update store/index.js

Now ‘store/index.js’ needs to be updated:

    import VuexPersist from 'vuex-persist'

    Vue.use(Vuex)

    const vuexPersist = new VuexPersist({
      key: 'vuedemo',
      storage: localStorage
    })

While creating Vue store, 

    plugins: [vuexPersist.plugin]

Load demo application, and change default_number_of_posts to ‘5’, then close browser and restart webpack server. Access the demo application again, and the value of ‘default_number_of_posts’ is reloaded from local storage.
  
## Curriculum

This is the 5th tutorial. More interesting topics will be covered in the following tutorials!

### Previous tutorials

[Part 1 - Build Steem blockchain application with Vue.js: installation and first demo](/@aafeng/part-1-build-steem-blockchain-application-using-vue-js-installation-and-first-demo)
[Part 2 - Build Steem blockchain application with Vue.js: components, computed properties and build/deployment process](/@aafeng/part-2-build-steem-blockchain-application-using-vue-js-components-computed-properties-and-build-deployment-process)
[Part 3 - Build Steem blockchain application with Vue.js: using Bootstrap, nav component, mixins, and first iteration of Posts component](/@aafeng/part-3-build-steem-blockchain-application-with-vue-js-using-bootstrap-mixins-and-first-iteration-of-posts-component)
[Part 4 - Build Steem blockchain application with Vue.js: dynamic route, and event handling](/@aafeng/part-4-build-steem-blockchain-application-with-vue-js-dynamic-route-and-event-handling)

## Proof of Work Done

Source code for this tutorial: https://github.com/aa-feng/VuejsTutorial/tree/t05

Master branch of the source code (will be updated with ongoing tutorials): https://github.com/aa-feng/VuejsTutorial

The live demo of latest iteration: https://vuetutorials.aafeng.top
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 155 others
properties (23)
authoraafeng
permlinkpart-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data
categoryutopian-io
json_metadata{"community":"steempeak","app":"steempeak/1.8.4b","format":"markdown","tags":["utopian-io","tutorials"],"users":["input","default","aafeng"],"links":["https://github.com/vuejs/vue","/@aafeng/part-1-build-steem-blockchain-application-using-vue-js-installation-and-first-demo","/@aafeng/part-2-build-steem-blockchain-application-using-vue-js-components-computed-properties-and-build-deployment-process","/@aafeng/part-3-build-steem-blockchain-application-with-vue-js-using-bootstrap-mixins-and-first-iteration-of-posts-component","/@aafeng/part-4-build-steem-blockchain-application-with-vue-js-dynamic-route-and-event-handling","https://github.com/aa-feng/VuejsTutorial/tree/t05","https://github.com/aa-feng/VuejsTutorial","https://vuetutorials.aafeng.top"],"image":["https://cdn.steemitimages.com/DQmSnFb8dojCSjhpeXagQowTaqY11zrwfaxbXJsffKyYY6T/image.png","https://cdn.steemitimages.com/DQmVhis22JXyGR1JtnLUYbUD4ggja93tHfvf5rVnePr9zMK/image.png","https://cdn.steemitimages.com/DQmZu9hjmVAViB369p8jdMBom1Vhv9LUvziJfsmCLGAw3wR/image.png","https://cdn.steemitimages.com/DQmZ6bDj2x4bpPwDNA3KHKEn4uwXRwYSuYm1P4q5nmVy9bU/image.png"]}
created2019-03-08 17:13:33
last_update2019-03-08 17:13:33
depth0
children6
last_payout2019-03-15 17:13:33
cashout_time1969-12-31 23:59:59
total_payout_value27.039 HBD
curator_payout_value8.818 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length10,977
author_reputation554,723,599,569,926
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries
0.
accountutopian.pay
weight500
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id80,929,596
net_rshares51,229,491,514,707
author_curate_reward""
vote details (219)
@portugalcoin · (edited)
$11.31
Thank you for your contribution @aafeng.
We've been reviewing your tutorial and suggest the following points below:

- We suggest that in the next tutorial put a shorter title, your title of this contribution is very extensive.

- At the end of your tutorial having a demo of your work is great, so the readers can experience what you have developed and have more insight than you built.

- Thanks for following our suggestions from the previous tutorial, your contribution is much better.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/2-2-3-1-1-3-1-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
👍  , , , , , , , , , , , , ,
properties (23)
authorportugalcoin
permlinkre-aafeng-part-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data-20190309t121104565z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["aafeng"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/2-2-3-1-1-3-1-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-03-09 12:11:03
last_update2019-03-09 12:11:21
depth1
children2
last_payout2019-03-16 12:11:03
cashout_time1969-12-31 23:59:59
total_payout_value8.612 HBD
curator_payout_value2.699 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,039
author_reputation599,460,335,323,040
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,962,823
net_rshares15,884,256,882,747
author_curate_reward""
vote details (14)
@aafeng ·
Thank you for your feedback, will take your suggestions in next tutorial.

Posted using [Partiko Android](https://steemit.com/@partiko-android)
properties (22)
authoraafeng
permlinkaafeng-re-portugalcoin-re-aafeng-part-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data-20190309t134233085z
categoryutopian-io
json_metadata{"app":"partiko","client":"android"}
created2019-03-09 13:42:36
last_update2019-03-09 13:42:36
depth2
children0
last_payout2019-03-16 13:42:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length143
author_reputation554,723,599,569,926
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,965,835
net_rshares0
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-aafeng-part-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data-20190309t121104565z-20190312t035538z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-03-12 03:55:39
last_update2019-03-12 03:55:39
depth2
children0
last_payout2019-03-19 03:55:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length64
author_reputation152,955,367,999,756
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,111,491
net_rshares0
@steem-ua ·
#### Hi @aafeng!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-part-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data-20190309t122426z
categoryutopian-io
json_metadata"{"app": "beem/0.20.18"}"
created2019-03-09 12:24:27
last_update2019-03-09 12:24:27
depth1
children0
last_payout2019-03-16 12:24:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length285
author_reputation23,214,230,978,060
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,963,294
net_rshares0
@steem-ua ·
#### Hi @aafeng!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-part-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data-20190309t123135z
categoryutopian-io
json_metadata"{"app": "beem/0.20.18"}"
created2019-03-09 12:31:36
last_update2019-03-09 12:31:36
depth1
children0
last_payout2019-03-16 12:31:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length285
author_reputation23,214,230,978,060
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,963,568
net_rshares0
@utopian-io ·
Hey, @aafeng!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-part-5-build-steem-blockchain-application-with-vue-js-passing-data-among-components-state-management-via-vuex-and-data-20190310t023948z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-03-10 02:39:51
last_update2019-03-10 02:39:51
depth1
children0
last_payout2019-03-17 02:39:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length588
author_reputation152,955,367,999,756
root_title"Part 5 - Build Steem blockchain application with Vue.js: Passing data among components, state management via Vuex, and data persistent in Vue.js"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,991,217
net_rshares0