Home >Web Front-end >Vue.js >How to use vuex to manage global data and status in Vue

How to use vuex to manage global data and status in Vue

WBOY
WBOYOriginal
2023-06-11 10:21:291224browse

Vue.js is a popular front-end framework that can build highly maintainable and reusable user interfaces. One of its main advantages is that it is very easy to learn and use, and works seamlessly with other libraries and frameworks. However, when your application starts to become more and more complex, you may encounter a problem: how to manage global state and data? This is the problem Vuex solves.

Vuex is a state management library designed specifically for Vue.js. Its main purpose is to make the maintenance of state more manageable. Vuex presents a single "source of data" and manages it in a predictable way.

In this article, we will introduce the basics of Vuex and demonstrate how to use it in Vue.js to manage global state and data.

Basic knowledge of Vuex

Before we go deep into Vuex, we need to have a basic understanding of its core concepts.

State

State is an object that stores application state. In Vuex, state is reactive, which means that when a state changes, all components using that state will automatically update. Normally you should initialize state to an empty object.

const store = new Vuex.Store({
    state: {
        count: 0
    }
})

Getter

Getter is a function used to get data from the state. Getter can be used when we need to calculate or filter the status. The getter accepts state as its first argument. Getters can be computed properties or functions.

const store = new Vuex.Store({
    state: {
        todos: [
            { id: 1, text: 'Todo 1', done: true },
            { id: 2, text: 'Todo 2', done: false }
        ]
    },
    getters: {
        doneTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        todoById: (state) => (id) => {
            return state.todos.find(todo => todo.id === id)
        }
    }
})

Mutation

Mutation is used to change the state. When changing state, you must use Mutation instead of changing the state directly. This convention allows us to track every state change and debug or backtrack as these changes occur. Mutation must be synchronous.

const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment (state) {
            state.count++
        }
    }
})

Action

Action is used to perform asynchronous tasks and submit Mutation. Actions often contain asynchronous logic, such as API calls. When an Action is called, it commits Mutations rather than changing state directly.

const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment (state) {
            state.count++
        }
    },
    actions: {
        incrementAsync ({ commit }) {
            setTimeout(() => {
                commit('increment')
            }, 1000)
        }
    }
})

Module

Vuex applications typically have a large state tree. To make the state tree maintainable, it can be split into several separate modules. Modules allow us to easily organize our code and isolate state.

const counterModule = {
    state: {
        count: 0
    },
    mutations: {
        increment (state) {
            state.count++
        }
    },
    actions: {
        incrementAsync ({ commit }) {
            setTimeout(() => {
                commit('increment')
            }, 1000)
        }
    }
}

const store = new Vuex.Store({
    modules: {
        counter: counterModule
    }
})

Managing global state with Vuex

Now that we understand the basics of Vuex, let’s see how to use it in a Vue.js application.

Installing Vuex

To use Vuex, first install it into your project. It can be installed using npm:

npm install vuex --save

After installation, you need to configure it into Vue.js by calling the Vue.use() method:

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

Vue.use(Vuex)

Define State

Let Let's create a very simple Todo List application to demonstrate how to use Vuex with Vue.js.

First we need to define an initial state, in this case we will define an array of todos:

const store = new Vuex.Store({
    state: {
        todos: [
            { id: 1, text: 'Todo 1', done: true },
            { id: 2, text: 'Todo 2', done: false },
            { id: 3, text: 'Todo 3', done: true }
        ]
    }
})

GetState

Now we define our state , let's see how to get the status using Getter.

Getter allows us to get data from the state and perform calculations. In our Todo List application, we can use Getters to get specific status or completed and unfinished todos.

const store = new Vuex.Store({
    state: {
        todos: [
            { id: 1, text: 'Todo 1', done: true },
            { id: 2, text: 'Todo 2', done: false },
            { id: 3, text: 'Todo 3', done: true }
        ]
    },
    getters: {
        allTodos: state => {
            return state.todos
        },
        completedTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        incompleteTodos: state => {
            return state.todos.filter(todo => !todo.done)
        }
    }
})

Change State

If you want to change the state, you need to use Mutation. Depending on our application, we can define two Mutation: add Todo and toggle completion status.

const store = new Vuex.Store({
    state: {
        todos: [
            { id: 1, text: 'Todo 1', done: true },
            { id: 2, text: 'Todo 2', done: false },
            { id: 3, text: 'Todo 3', done: true }
        ]
    },
    getters: {
        allTodos: state => {
            return state.todos
        },
        completedTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        incompleteTodos: state => {
            return state.todos.filter(todo => !todo.done)
        }
    },
    mutations: {
        addTodo: (state, todo) => {
            state.todos.push(todo)
        },
        toggleTodo: (state, id) => {
            const todo = state.todos.find(todo => todo.id === id)
            todo.done = !todo.done
        }
    }
})

Perform Actions

In our Todo List application, we may need to perform some asynchronous operations. For example, if you want to get todos from the server, you have to use an asynchronous Action.

const store = new Vuex.Store({
    state: {
        todos: [
            { id: 1, text: 'Todo 1', done: true },
            { id: 2, text: 'Todo 2', done: false },
            { id: 3, text: 'Todo 3', done: true }
        ]
    },
    getters: {
        allTodos: state => {
            return state.todos
        },
        completedTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        incompleteTodos: state => {
            return state.todos.filter(todo => !todo.done)
        }
    },
    mutations: {
        addTodo: (state, todo) => {
            state.todos.push(todo)
        },
        toggleTodo: (state, id) => {
            const todo = state.todos.find(todo => todo.id === id)
            todo.done = !todo.done
        }
    },
    actions: {
        loadTodos: ({ commit }) => {
            api.getTodos(todos => {
                todos.forEach(todo => {
                    commit('addTodo', todo)
                })
            })
        }
    }
})

Using Modules

As your Vuex state becomes more complex, you may need to split it into multiple modules.

In our application, we can split the Todo List application state into two modules: Todo and User. The Todo module contains Todo list data and related operations. The User module contains user information.

const todoModule = {
    state: {
        todos: [
            { id: 1, text: 'Todo 1', done: true },
            { id: 2, text: 'Todo 2', done: false },
            { id: 3, text: 'Todo 3', done: true }
        ]
    },
    getters: {
        allTodos: state => {
            return state.todos
        },
        completedTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        incompleteTodos: state => {
            return state.todos.filter(todo => !todo.done)
        }
    },
    mutations: {
        addTodo: (state, todo) => {
            state.todos.push(todo)
        },
        toggleTodo: (state, id) => {
            const todo = state.todos.find(todo => todo.id === id)
            todo.done = !todo.done
        }
    },
    actions: {
        loadTodos: ({ commit }) => {
            api.getTodos(todos => {
                todos.forEach(todo => {
                    commit('addTodo', todo)
                })
            })
        }
    }
}

const userModule = {
    state: {
        user: null
    },
    mutations: {
        setUser: (state, user) => {
            state.user = user
        },
        clearUser: (state) => {
            state.user = null
        }
    },
    actions: {
        login: ({ commit }, user) => {
            api.login(user, () => {
                commit('setUser', user)
            })
        },
        logout: ({ commit }) => {
            api.logout(() => {
                commit('clearUser')
            })
        }
    }
}

const store = new Vuex.Store({
    modules: {
        todo: todoModule,
        user: userModule
    }
})

Summary

Vuex is a very powerful state management library that helps us elegantly manage the state and data of Vue.js applications. By using Vuex, we can easily access and change global state without having to manually pass data between components. Remember, best practice is to use Vuex on demand, when needed. For simple applications, just using local component state may be enough to fully meet your needs. However, if your application becomes increasingly complex, you may consider using Vuex to manage state.

The above is the detailed content of How to use vuex to manage global data and status in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn