Debbie Clay

Debbie Clay

1560931335

Getting Started with Vuex: Managing State in Vue.js

Table of Contents

  1. State Management
  2. Setting up Vue and Vuex
  3. Vuex Overview
  4. Vuex State
  5. Vuex Getters
  6. Vuex Mutations
  7. Vuex Actions
  8. Vuex Store
  9. Building our Vue Components
  10. The Markup and Styles
  11. Conclusion

Breaking down larger pieces of an app into smaller components has become really popular thanks to the rise of front-end libraries like React and Vue. Components allow you to easily reuse code, reduce architectural complexity, and build impressive user interfaces by logically dividing your code into independent chunks.

However, despite these advantages, one issue that eventually hits any application that grows large enough is the difficulty of managing its state. Facebook’s answer to this challenge was Flux, a pattern that later served as the basis for the more popular Redux state management library that is commonly used with React.

The Vue team, realizing that their library would also need a way to manage state, introduced Vuex, the official state management library for Vue.

In this tutorial, we will be diving into Vuex by building a nice todo app. Make sure that you are comfortable with both JavaScript and Vue before continuing with this tutorial. This is what we will be building:

The todo list app we’ll be building.

You can check out a live demo of the finished app here.

State Management

As mentioned before, state management becomes tricky when your app becomes larger and more complex. You can get away without standalone state management if your app is small, but as it grows, your code could easily become a nightmare to debug and iterate upon.

The state of an application is a collection of variables and their values at that point in time (basically the data powering your app). For example, if you open a calculator app for the first time, its current total would be 0 so its state could look like this:

	
    {
        total: 0
    }
	

After you evaluate 2 + 4, its state could look like this:

	
    {
        total: 6
    }
	

This is where Vuex comes into play. It offers you a clear and organized way to initialize, manage, and modify your Vue application’s state in a straightforward and easy-to-track way.

Setting up Vue and Vuex

Create a folder to serve as the root directory for this app, and create three files in that folder, index.html to contain our markup, styles.css for our styles, and app.js for our code.

Put this inside your index.html:

	
    <html>
        <head>
            <title>Todo List</title>
            <link rel="stylesheet" href="styles.css">
        </head>
        <body>
            <div class="container">
                <h1>Todo List</h1>
                <div id="app"></div>
            </div>
            <script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></script>
            <script src="https://unpkg.com/vuex@3.0.1/dist/vuex.min.js"></script>
            <script src="app.js"></script>
        </body>
    </html>
	

This pulls in our styles from styles.css and imports the following three JavaScript files:

  1. Vue from the Unpkg CDN
  2. Vuex from the Unpkg CDN
  3. Our app.js script in our folder

At this point, your project folder should look like this:

Your project folder.

Vuex Overview

The whole idea behind Vuex is confusing at first but becomes clear with time. A simple overview of Vuex and its most important concepts are critical to be familiar with as it will make building this app (and future ones) much easier.

In Vuex, you have something called the store. The store is a global object that contains four major things that Vuex needs to manage state in our Vue app. We’ll go over each four below.

The first thing our store needs is the state. This is Vuex’s bread and butter. The state is the JavaScript object that contains the actual data that your app needs to function.

We can retrieve data from the store by defining the getters of the store and then calling them when we need to. The getters are just functions that get the data from the state for you.

Now that we can get data from the state, we need a way to change or modify it. For example, when a new calculation is evaluated on a calculator, you’d want the total to be updated. This changing of the state is called mutating it. Thus, changes to the state are also called mutations.

One final thing to keep in mind is that even though mutations are what actually modify the state, the functions should not be called directly. Mutations to the state should only be called by separate functions called actions.

The idea here is that while you technically can just directly mutate the state to your liking, action functions that themselves call mutations ensure we can modify our state in a predictable, safe, and clean way.

So, to recap, here are the four major concepts of a Vuex store:

  1. State: The object that holds your app’s data.
  2. Getters: Functions that return back data contained in the state.
  3. Mutations: Functions that directly mutate the state, as the state is an immutable object.
  4. Actions: Functions that call mutations on the state. They can call multiple mutations, can call other actions, and they support asynchronous operations.

Here is a diagram of Vuex which should hopefully make more clear what is going on:

A diagram of Vuex from the official project Github page.

Users will interact with the Vue components on their screen. Some of these interactions will trigger action functions that then commit mutations on the state. After the state has been mutated, Vue uses this new state to re-render the affected components on the screen.

Now, let’s get to some implementing!

Vuex State

The first step in using Vuex is simply deciding on what pieces of data your app will need to function properly, the state. Recall that we are building a todo list app. With that in mind, it is logical to conclude that in our simple example we will only need a single thing to hold in our state, the array of todo items.

Each todo item should contain a string that describes the task and then a boolean to keep track of whether or not the item was completed. Also, to keep track of our items, we’ll give them each a unique ID number.

Here is the state of our Vue app, initialized with three example todo items.

	
    var state = {
        todos: [
            {
                id: 0,
                task: "Buy food at the supermarket.",
                completed: false
            },
            {
                id: 1,
                task: "Organize the living room.",
                completed: true
            },
            {
                id: 2,
                task: "Read every class and tutorial on Sabe.io.",
                completed: false
            }
        ]
    };
	

Vuex Getters

Luckily for us, in this example, our state only contains a single thing, the array of our todo items. Because of this simplicity, we only need a single getter function that retrieves the entire array.

	
    var getters = {
        getTodos: state => state.todos
    };
	

The getTodos() function takes the state object that we defined (and that Vuex passed in automatically for us), and simply returns the todos array for us.

Onwards to mutations!

Vuex Mutations

Recall that the only job of mutation functions is to mutate, or modify, the state. In our example, there are three things we would ever need to do to our state:

  1. Add a new item: When we want a new todo item, we should be able to add it to the array.
  2. Toggle the completion: We should be able to go back and forth between the two completion states of a task.
  3. Delete an item: When we no longer want a todo item, we should be able to remove it from the array.

Keeping this in mind, here are our three mutations:

	
    var mutations = {
        ADD_TODO: (state, payload) => {

            var newTask = {
                id: payload.newId,
                task: payload.task,
                completed: false
            }

            state.todos.unshift(newTask);
        },
        TOGGLE_TODO: (state, payload) => {
            var item = state.todos.find(todo => todo.id === payload);
            item.completed = !item.completed;
        },
        DELETE_TODO: (state, payload) => {
            var index = state.todos.findIndex(todo => todo.id === payload);
            state.todos.splice(index, 1);
        }
    };
	

Per convention, mutation functions are capitalized to distinguish them from other functions.

Mutation functions, in addition to getting access to the state, also get access to a payload, which is just the information needed to make the mutation. In the case of ADD_TODO the payload is all the information needed to create a brand new todo item, and in the case of TOGGLE_TODO and DELETE_TODO, we only care about the ID of the todo item, so we only passed that in.

Ultimately in all three mutation functions, we are just doing basic array manipulation:

  1. In ADD_TODO, we are simply creating a brand new item and adding it to the array via unshift.
  2. In TOGGLE_TODO, we are finding the todo item in the array via its unique ID, then inverting its completed boolean.
  3. In DELETE_TODO, we are finding the todo item in the array and then removing it via splice.

Vuex Actions

The final piece of the puzzle is our action functions. Again, recall that these functions exist to call mutator functions. They’re going to be straightforward in this case, but in more complex apps, they are used to perform asynchronous actions and evaluate some logic before making the actual mutations on the state.

Because we don’t need to do much here, our action functions are going to be extremely simple.

	
    var actions = {
        addTodo: (context, payload) => {
            context.commit("ADD_TODO", payload)
        },
        toggleTodo: (context, payload) => {
            context.commit("TOGGLE_TODO", payload)
        },
        deleteTodo: (context, payload) => {
            context.commit("DELETE_TODO", payload)
        }
    }
	

Don’t let terms confuse you, context is just the store and commit is just the function name that calls a mutation function with the provided payload.

The first parameter of the commit function is the name of the mutation, then the second parameter is the payload needed to make that mutation. In our case, we just pass along the payload given to our action functions.

Vuex Store

At last, we have all four pieces and can finally put it all together to have a working Vuex store for our app. Now all we need to do is define a new store and pass everything we just defined in:

	
    var store = new Vuex.Store({
        state: state,
        getters: getters,
        mutations: mutations,
        actions: actions
    });
	

We are now completely ready to start incorporating the use of our store inside our Vue app, so let’s start on that!

Building our Vue Components

Believe it or not but with our store fully defined and ready to go, we have already built the majority of this app. The rest from this point on is just building the user interface for it.

Ideally for our app we are going to want two components, the component that contains the list of todo items, and then the overall component that contains the entire app, including the form that you use to create new todo items.

Todo Items List Component

We’ll start with the todo items list component:

	
    Vue.component("todo-list", {
        computed: {
            todos() {
                return this.$store.getters.getTodos;
            }
        },
        methods: {
            toggleTodo: function(id) {
                this.$store.dispatch("toggleTodo", id);
            },
            deleteTodo: function(id) {
                this.$store.dispatch("deleteTodo", id);
            }
        },
        template: "#todo-list"
    });
	

For the list to render properly, it needs the todo items from the store, and so we’ll make it accessible via a computed property that returns it from the store. Since the parent is taking care of adding, we only need to support toggling and deleting, and thus we have the two methods toggleTodo and deleteTodo.

If you’ve noticed, both of these methods just do one thing: dispatches an action. They pass in the ID of the todo item being affected as the payload to be used by the action function (and later the mutator function).

Finally, we set the template to #todo-list so that Vue knows where to get the markup to use for this component.

Todo Parent Container Component

With the list component ready to go, the last part left is defining the Vue app itself that will serve as the glue that holds everything together, and here it is:

	
    var app = new Vue({
        data: () => ({
            task: "",
            newId: 3
        }),
        methods: {
            addTodo: function() {
                this.$store.dispatch("addTodo", this);
                this.newId ++;
                this.task = "";
            }
        },
        store: store,
        el: "#app",
        template: "#app-template"
    });
	

The data function initializes the task string to being empty so that the user is free to create a brand new task, and newId is set to 3 because we already have three items and want every todo item to have a unique ID. If you initialize the app with more or less todo items, you will have to adjust this variable’s initial value.

Under methods, we define the addTodo function which dispatches the addTodo action, passing in this as the payload (which includes the current value for task and the id of the new task item). After the action is dispatched, we increment the newId property so that the next task’s ID is ready to go, and reset the value of the task string.

Finally, we pass in the store we defined to Vue, the element we want Vue to mount on, #app, and then the template we want to use, #app-template.

The Markup and Styles

With all the JavaScript in place, it’s time to go back and bring our index.html and styles.css files up to speed. Since we defined two new templates for our Vue components, #todo-list and #app-template, we must provide them to Vue.

Add this to your index.html directly above your JavaScript script tags.

	
    <template id="todo-list">
        <ul class="tasks">
            <li v-for="todo in todos"
                :class="{completed: todo.completed}"
                class="task"
                @click="toggleTodo(todo.id)"
                @dblclick="deleteTodo(todo.id)">{{todo.task}}</li>
        </ul>
    </template>
    <template id="app-template">
        <div>
            <form @submit.prevent="addTodo">
                <input class="todo-input" type="text" placeholder="Enter a new Task" v-model="task" />
            </form>
            <todo-list />
        </div>
    </template>
	

At this point, your app should technically work completely and offer these features:

  1. Type a new task and press enter to add it to the list.
  2. Click on a task to toggle its completion status.
  3. Double-click on a task to remove it completely.

However, we want to make our todo list app look pretty. 😍 Open your styles.css and add this:

	
    html {
        font-family: sans-serif;
        background: linear-gradient(45deg, #6cfd9f, #6887ff);
        height: 100%;
        color: #333;
    }
    body {
        display: flex;
        height: 100%;
        margin: 0;
    }
    .container {
        width: 24rem;
        margin: auto;
        background-color: white;
        border-radius: 0.5rem;
        padding: 1rem;
        box-shadow: 0 0 2rem rgba(0, 0, 0, 0.25);
    }
    h1 {
        text-align: center;
        margin-top: 0;
    }
    .todo-input {
        width: 100%;
        padding: 0.5rem;
        font-size: 1rem;
        outline: none;
        border-radius: 0.25rem;
        border-style: none;
        border: solid 1px lightgray;
        box-sizing: border-box;
    }
    .tasks {
        padding-left: 1.5rem;
    }
    .task {
        margin-bottom: 0.5rem;
    }
    .task:hover {
        cursor: pointer;
    }
    .completed {
        text-decoration: line-through;
        color: #555;
    }
	

Conclusion

Your app is now ready to go. Open index.html and see the power of Vuex right before your very eyes.

The todo list app you built.

Again, you can check out a live demo here.

Recall that when you do stuff like add a new todo item, invert its completion boolean, or delete it, here is what is actually happening under the hood:

  1. You first do something.
  2. This triggers an action and a payload is passed in.
  3. Actions then call mutations on the state, and pass in a payload.
  4. Mutation functions alter the state with that payload.
  5. Vue automatically re-renders what it needs to re-render given this new state.

I hope that this example app has illustrated just how powerful Vuex can be. On a much bigger application, having standalone state management with Vuex would be crucial for clean code.

#vue-js #javascript

What is GEEK

Buddha Community

Getting Started with Vuex: Managing State in Vue.js
Aria Barnes

Aria Barnes

1625232484

Why is Vue JS the most Preferred Choice for Responsive Web Application Development?

For more than two decades, JavaScript has facilitated businesses to develop responsive web applications for their customers. Used both client and server-side, JavaScript enables you to bring dynamics to pages through expanded functionality and real-time modifications.

Did you know!

According to a web development survey 2020, JavaScript is the most used language for the 8th year, with 67.7% of people choosing it. With this came up several javascript frameworks for frontend, backend development, or even testing.

And one such framework is Vue.Js. It is used to build simple projects and can also be advanced to create sophisticated apps using state-of-the-art tools. Beyond that, some other solid reasons give Vuejs a thumbs up for responsive web application development.

Want to know them? Then follow this blog until the end. Through this article, I will describe all the reasons and benefits of Vue js development. So, stay tuned.

Vue.Js - A Brief Introduction

Released in the year 2014 for public use, Vue.Js is an open-source JavaScript framework used to create UIs and single-page applications. It has over 77.4 million likes on Github for creating intuitive web interfaces.

The recent version is Vue.js 2.6, and is the second most preferred framework according to Stack Overflow Developer Survey 2019.

Every Vue.js development company is widely using the framework across the world for responsive web application development. It is centered around the view layer, provides a lot of functionality for the view layer, and builds single-page web applications.

Some most astonishing stats about Vue.Js:

• Vue was ranked #2 in the Front End JavaScript Framework rankings in the State of JS 2019 survey by developers.

• Approximately 427k to 693k sites are built with Vue js, according to Wappalyzer and BuiltWith statistics of June 2020.

• According to the State of JS 2019 survey, 40.5% of JavaScript developers are currently using Vue, while 34.5% have shown keen interest in using it in the future.

• In Stack Overflow's Developer Survey 2020, Vue was ranked the 3rd most popular front-end JavaScript framework.

Why is Vue.Js so popular?

• High-speed run-time performance
• Vue.Js uses a virtual DOM.
• The main focus is on the core library, while the collaborating libraries handle other features such as global state management and routing.
• Vue.JS provides responsive visual components.

Top 7 Reasons to Choose Vue JS for Web Application Development

Vue js development has certain benefits, which will encourage you to use it in your projects. For example, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy increasing popularity compared to other frameworks.

The framework is only 20 kilobytes in size, making it easy for you to download files instantly. Vue.js easily beats other frameworks when it comes to loading times and usage.

Take a look at the compelling advantages of using Vue.Js for web app development.

#1 Simple Integration

Vue.Js is popular because it allows you to integrate Vue.js into other frameworks such as React, enabling you to customize the project as per your needs and requirements.

It helps you build apps with Vue.js from scratch and introduce Vue.js elements into their existing apps. Due to its ease of integration, Vue.js is becoming a popular choice for web development as it can be used with various existing web applications.

You can feel free to include Vue.js CDN and start using it. Most third-party Vue components and libraries are additionally accessible and supported with the Vue.js CDN.

You don't need to set up node and npm to start using Vue.js. This implies that it helps develop new web applications, just like modifying previous applications.

The diversity of components allows you to create different types of web applications and replace existing frameworks. In addition, you can also choose to hire Vue js developers to use the technology to experiment with many other JavaScript applications.

#2 Easy to Understand

One of the main reasons for the growing popularity of Vue.Js is that the framework is straightforward to understand for individuals. This means that you can easily add Vue.Js to your web projects.

Also, Vue.Js has a well-defined architecture for storing your data with life-cycle and custom methods. Vue.Js also provides additional features such as watchers, directives, and computed properties, making it extremely easy to build modern apps and web applications with ease.

Another significant advantage of using the Vue.Js framework is that it makes it easy to build small and large-scale web applications in the shortest amount of time.

#3 Well-defined Ecosystem

The VueJS ecosystem is vibrant and well-defined, allowing Vue.Js development company to switch users to VueJS over other frameworks for web app development.

Without spending hours, you can easily find solutions to your problems. Furthermore, VueJs lets you choose only the building blocks you need.

Although the main focus of Vue is the view layer, with the help of Vue Router, Vue Test Utils, Vuex, and Vue CLI, you can find solutions and recommendations for frequently occurring problems.

The problems fall into these categories, and hence it becomes easy for programmers to get started with coding right away and not waste time figuring out how to use these tools.

The Vue ecosystem is easy to customize and scales between a library and a framework. Compared to other frameworks, its development speed is excellent, and it can also integrate different projects. This is the reason why most website development companies also prefer the Vue.Js ecosystem over others.

#4 Flexibility

Another benefit of going with Vue.Js for web app development needs is flexibility. Vue.Js provides an excellent level of flexibility. And makes it easier for web app development companies to write their templates in HTML, JavaScript, or pure JavaScript using virtual nodes.

Another significant benefit of using Vue.Js is that it makes it easier for developers to work with tools like templating engines, CSS preprocessors, and type checking tools like TypeScript.

#5 Two-Way Communication

Vue.Js is an excellent option for you because it encourages two-way communication. This has become possible with the MVVM architecture to handle HTML blocks. In this way, Vue.Js is very similar to Angular.Js, making it easier to handle HTML blocks as well.

With Vue.Js, two-way data binding is straightforward. This means that any changes made by the developer to the UI are passed to the data, and the changes made to the data are reflected in the UI.

This is also one reason why Vue.Js is also known as reactive because it can react to changes made to the data. This sets it apart from other libraries such as React.Js, which are designed to support only one-way communication.

#6 Detailed Documentation

One essential thing is well-defined documentation that helps you understand the required mechanism and build your application with ease. It shows all the options offered by the framework and related best practice examples.

Vue has excellent docs, and its API references are one of the best in the industry. They are well written, clear, and accessible in dealing with everything you need to know to build a Vue application.

Besides, the documentation at Vue.js is constantly improved and updated. It also includes a simple introductory guide and an excellent overview of the API. Perhaps, this is one of the most detailed documentation available for this type of language.

#7 Large Community Support

Support for the platform is impressive. In 2018, support continued to impress as every question was answered diligently. Over 6,200 problems were solved with an average resolution time of just six hours.

To support the community, there are frequent release cycles of updated information. Furthermore, the community continues to grow and develop with backend support from developers.



Wrapping Up

VueJS is an incredible choice for responsive web app development. Since it is lightweight and user-friendly, it builds a fast and integrated web application. The capabilities and potential of VueJS for web app development are extensive.

While Vuejs is simple to get started with, using it to build scalable web apps requires professionalism. Hence, you can approach a top Vue js development company in India to develop high-performing web apps.

Equipped with all the above features, it doesn't matter whether you want to build a small concept app or a full-fledged web app; Vue.Js is the most performant you can rely on.

Original source

 

#vue js development company #vue js development company in india #vue js development company india #vue js development services #vue js development #vue js development companies

sophia tondon

sophia tondon

1618971133

Top 10 VueJS Development Companies To Know In 2021-22

Vue.js is one of the most used and popular frontend development, or you can say client-side development framework. It is mainly used to develop single-page applications for both web and mobile. Famous companies like GitLab, NASA, Monito, Adobe, Accenture are currently using VueJS.

Do You Know?

Around 3079 companies reportedly use Vue.js in their tech stacks.
At GitHub, VueJS got 180.9K GitHub stars, including 28.5K GitHub forks.
Observing the increasing usage of VueJS and its robust features, various industry verticals are preferring to develop the website and mobile app Frontend using VueJS, and due to this reason, businesses are focusing on hiring VueJS developers from the top Vue.js development companies.

But the major concern of the enterprises is how to find the top companies to avail leading VueJS development service? Let’s move further and know what can help you find the best VueJS companies.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-10-vuejs-development-companies/

#hire vue js developer #hire vue.js developers #hire vue.js developer, #hire vue.js developers, #vue js development company #vue.js development company

Luna  Mosciski

Luna Mosciski

1600583123

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.

Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.

Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.

Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.

“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You

#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js

Top VueJS App Development Company in USA

AppClues Infotech is the best & most reliable VueJS App Development Company in USA that builds high-quality and top-notch mobile apps with advanced methodology. The company is focused on providing innovative & technology-oriented solutions as per your specific business needs.

The organization’s VueJS developers have high experience and we have the capability of handling small to big projects. Being one of the leading mobile app development company in USA we are using the latest programming languages and technologies for their clients.

Key Elements:

· Total year of experience - 8+

· Employees Strength - 120+

· Hourly Rate - $25 – $45 / hr

· Location - New York, USA

· Successfully launched projects - 450+

VueJS Development Services by AppClues Infotech

· Custom VueJS Development

· Portal Development Solutions

· Web Application Development

· VueJS Plugin Development

· VueJS Ecommerce Development

· SPA (Single Page App) Development

· VueJS Migration

Why Hire VueJS Developers from AppClues Infotech?

· Agile & Adaptive Development

· 8+ Years of Average Experience

· 100% Transparency

· Guaranteed Bug-free VueJS Solution

· Flexible Engagement Models

· On-Time Project Delivery

· Immediate Technical Support

If you have any project ideas for VueJS app development then share your requirements with AppClues Infotech to get the best solution for your dream projects.

For more info:
Share Yoru Requirements: https://www.appcluesinfotech.com/contact-us/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910
**

#top vue.js development company #vue.js app development company #best vue js development company #hire top vue js developers #hire top vue.js developers in usa #vue js development company usa