State management with Vuex

Before we introduce Vuex, let's take a look at different methods of state management in different web apps.

In a traditional web application that creates fresh pages when navigating through hyperlinks, there is very little state management required because the state is lost once users navigate to another page. In these applications, pages are generated dynamically on the backend. Most of the state of the application is kept on the server side.

Another type of web application is a single-page application (SPA). Different from a traditional app, an SPA has no page refreshes and it moves some of the logic from the backend to the frontend. Accordingly, it needs to keep some of the states on the client side. This brings complexity to frontend development. With frameworks such as Backbone.js, patterns similar to MVC are introduced into the frontend. (These patterns are usually referred to as MV*.) And, usually, the state of the application is kept inside global variables or, if you're using a library like RequireJS, you will define a data model in a JS file and import it into other modules. The code that imports the data model can do anything to it, even replacing it entirely. It is true that you can add some protection to the data model, but you cannot control the data flow, as you will see in the next section when we talk about the drawbacks of traditional state management.

Nowadays, when we create an SPA, such as our TaskAgile application, without using Vuex, we can create a single object and store state in that object and share it across Vue components. For example, we can create front-end/src/local-data.js as follows:

export default {
name: 'Unknown'
}

And we can then import it into different Vue components, for example, front-end/src/components/ComponentA.vue, as follows:

<template>
<div>{{ name }} in Component A</div>
</template>
<script>
Import localData from '../local-data'
export default {
data: function () {
return localData
}
}
</script>

Vue component front-end/src/components/ComponentB.vue, as follows:

<template>
<div>{{ name }} in Component B</div>
</template>
<script>
Import localData from '../local-data'
export default {
data: function () {
return localData
},
mounted: function () {
this.name = 'Sunny'
}
}
</script>

As you can see, inside the <template> sections of both components, we can reference the name property defined in local-data.js directly. In ComponentB, we can change its value. This change will be updated to ComponentA automatically. Vue.js takes care of that, which is quite convenient.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.1