Vuex, Vue.js state manager

Vuex is the official state management library for Vue.js. In this tutorial, I will explain its basic usage.

Introduction to Vuex

Vuex is the official state management library for Vue.js.

Its job is to share data between the various components of the application.

Components in Vue.js out of the box can be used

  • PropsTo pass state from parent to child component
  • Memorabilia, Change the state of the parent component from the child, or use the root component as an event bus

Sometimes things get more complicated than these simple options allow.

In this case, a good choice is to centralize the state in one storage. This is what Vuex does.

Why use Vuex

Vuex is not the only state management option you can use in Vue (you can useReduxThe same is true), but its main advantage is that it is official, and the integration with Vue.js makes it shine.

With React, you will have to choose one of the many available libraries because the ecosystem is huge and there are no actual standards. Recently, Redux is the most popular choice, followed by MobX in popularity. With Vue, what I want to say is that besides Vuex, you don't need to look around for other things, especially when you start learning.

Vuex borrowed many ideas from the React ecosystem because this is a popular Flux pattern in Redux.

If you already know Flux or Redux, then Vuex will be very familiar. If you don't have one, then no problem-I will explain each concept thoroughly.

Components in a Vue application can have their own state. For example, an input box will store the data entered into it locally. This is very good, even with Vuex, components can have local state.

You know that you need something like Vuex to start doing a lot of work to pass state.

In this case, Vuex provides a central repository for the state, and you can make changes to the state by requesting the state.

Every component that depends on a specific part of the state will use a getter in the store to access it to ensure that it is updated as soon as the state changes.

Using Vuex will bring some complexity to the application, because it needs to be set in a certain way to work properly, but if this helps to solve the unorganized prop delivery and event system (if it is too complex, it may become Spaghetti), then a good choice.

let's start

In this example, I started from aVue CLIapplication. You can also use Vuex by directly loading Vuex into the script tag, but since Vuex is more suitable for large applications, you are likely to use it on structured applications, such as applications that can be quickly launched through Vue. CLI.

The examples I use will be placed in CodeSandbox, it is a great service, with ready Vue CLI exampleshttps://codesandbox.io/s/vue. I recommend using it to play.

CodeSandbox

After you arrive, please clickAdd dependencyButton, enter "vuex" and click on it.

Now, Vuex will be listed in the project dependencies.

To install Vuex locally, you can runnpm install vuexoryarn add vuexIn the project folder.

Create a Vuex store

Now, we are ready to create a Vuex store.

The file can be placed anywhere. It is generally recommended to put it insrc/store/store.jsFile, so we will do it.

In this file, we initialize Vuex and tell Vue to use it:

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

Vue.use(Vuex)

export const store = new Vuex.Store({})

Vuex store

We export the Vuex store object, which is usedVuex.Store()API.

Use cases for stores

Now that we have a framework, let us come up with an idea of a good use case for Vuex so that I can introduce its concept.

For example, I have 2 components at the same level, one with an input field, and the other prints the content of the input field.

When the input field changes, I also need to change the content in the second component. It's simple, but this will do the work for us.

Introduce the new components we need

I deleted the HelloWorld component and added a Form component and a Display component.

<template>
	<div>
		<label for="flavor">Favorite ice cream flavor?</label>
		<input name="flavor">
	</div>
</template>
<template>
	<div>
		<p>You chose ???</p>
	</div>
</template>

Add these components to the application

We add them to the App.vue code instead of the HelloWorld component:

<template>
  <div id="app">
    <Form/>
    <Display/>
  </div>
</template>

<script> import Form from ‘./components/Form’ import Display from ‘./components/Display’

export default { name: ‘App’, components: { Form, Display } } </script>

Add status to store

So with this, we go back to the store.js file and add an attribute to the store calledstate, Which is an object that containsflavorproperty. Initially an empty string.

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

Vue.use(Vuex)

export const store = new Vuex.Store({ state: { flavor: ‘’ } })

When the user types in the input field, we will update it.

Add a mutation

This state can only be manipulated by usingMutations. We set up a mutation, which will be used inside the Form component to notify the store that the state should change.

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

Vue.use(Vuex)

export const store = new Vuex.Store({ state: { flavor: ‘’ }, mutations: { change(state, flavor) { state.flavor = flavor } } })

Add getter to refer to state attributes

After setting up, we need to add a way to view the status. We useGetter. We areflavorproperty:

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

Vue.use(Vuex)

export const store = new Vuex.Store({ state: { flavor: ‘’ }, mutations: { change(state, flavor) { state.flavor = flavor } }, getters: { flavor: state => state.flavor } })

Pay attention to howgettersIs an object.flavorIs a property of this object, the object accepts state as a parameter and returnsflavorState property.

Add the Vuex store to the app

Now the store is ready and ready to use. Let's go back to the application code, in the main.js file, we need to import the state and make it available in our Vue application.

We increase

import { store } from './store/store'

And add it to the Vue application:

new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

Once this code is added, since it is the main component of Vue,storeThe variables in each Vue component will point to Vuex storage.

Use submit to update the status of a user action

Let's update the status as the user types.

We usestore.commit()API.

But first, let's create a method that is called when the input changes. we use@inputInstead of@changeBecause the latter is only triggered when the focus is removed from the input box, and@inputIt will be called every time a key is pressed.

<template>
  <div>
    <label for="flavor">Favorite ice cream flavor?</label>
    <input @input="changed" name="flavor">
  </div>
</template>

<script> export default { methods: { changed: function(event) { alert(event.target.value) } } } </script>

Now that we have the value of flavor, we use the Vuex API:

<script>
export default {
  methods: {
    changed: function(event) {
      this.$store.commit('change', event.target.value)
    }
  }
}
</script>

See how we usethis.$store? This is due to the inclusion of storage objects in the initialization of the main Vue component.

Thiscommit()Method accepts a mutation name (we usedchange(In Vuex storage) and payloads, which will be passed to the mutation as the second parameter of the callback function.

Use getter to print status value

Now, we need to use the following method to reference the method of obtaining the value in the "display" template:$store.getters.flavor.thisCan be deleted because we are in the template andthisIs implicit.

<template>
  <div>
    <p>You chose {{ $store.getters.flavor }}</p>
  </div>
</template>

wrap up

It's an introduction to Vuex!

The complete and valid source code is available at:https://codesandbox.io/s/zq7k7nkzkm

Many concepts are still missing in this puzzle:

  • action
  • Module
  • helper
  • Plug-in

But you have the basic knowledge to read in the official documentation.

Happy coding!

Download mine for freeVue manual


More vue tutorials: