Practical sharing on using vuex to manage global status in Vue
Vue is a popular front-end framework. Its basic idea is to divide the page into different components, each component has its own state. However, there are situations where we need to share state between multiple components. To deal with this situation, Vue provides vuex, a third-party library specifically designed to manage the global state of the application. In this article, we will share some practical experiences using vuex in Vue projects.
What is Vuex?
Vuex is the official state management tool for Vue.js. It uses a centralized storage to manage the state of all components of the application, implemented through a single object.
The core concepts of Vuex include:
- State: Stores application-level state.
- Getter: Get the value stored in state and perform calculations.
- Mutation: Change the value in state.
- Action: Submit mutation and perform asynchronous operation.
- Module: Decompose the store into multiple sub-modules. Each module can have its own state, mutation, action
Use Vuex in the Vue project
For To demonstrate the process of using Vuex in a Vue project, we will create a simple sample application we call "ToDo List" that allows us to add and remove tasks and display them in a task list. Below we will introduce how to use Vuex to implement this ToDo List application.
First, in order to use Vuex, we need to import it in our Vue application. We can import and inject the Vuex object in main.js as follows:
import Vue from 'vue' import Vuex from 'vuex' import App from './App.vue' Vue.use(Vuex) const store = new Vuex.Store({ state: { tasks: [] }, mutations: { addTask(state, task) { state.tasks.push(task) }, removeTask(state, index) { state.tasks.splice(index, 1) } } }) new Vue({ store, render: h => h(App) }).$mount('#app')
Here, we first import Vuex and inject it into the Vue object. Next, we will create a constant called store that creates a new Vuex storage instance using the Vuex.Store constructor. Here we define the state and mutations in our store. Our status is the tasks array, which stores the tasks in our ToDo List. Our mutations include addTask and removeTask, which are used to add and remove tasks respectively.
We also inject the store into the Vue instance so we can use it in all components of our application. Now, we can access the state and mutations in the store in our component.
In our sample ToDo List application, we have a component called AddTask.vue that contains a form that allows the user to add tasks. In this component, we can use $store to access the state and mutations in the store, and trigger our addTask mutation to add the task to the store. The code is as follows:
<template> <form @submit.prevent="addTask"> <input type="text" v-model="task" /> <button type="submit">Add Task</button> </form> </template> <script> export default { data() { return { task: '' } }, methods: { addTask() { this.$store.commit('addTask', this.task) this.task = '' } } } </script>
Here, we use a form in the component, and when the form is submitted, we call the addTask method and pass the task name as a parameter to the $store.commit method. This triggers the addTask mutation we defined earlier to add the task to the store.
Next, we have a TasksList.vue component that displays a list of tasks and allows the user to delete tasks. In this component, we can use $store to access the state and mutations in the store, and trigger our removeTask mutation to remove the task from the store. The code is as follows:
<template> <ul> <li v-for="(task, index) in tasks" :key="index"> {{ task }} <button @click="removeTask(index)">Remove Task</button> </li> </ul> </template> <script> export default { computed: { tasks() { return this.$store.state.tasks } }, methods: { removeTask(index) { this.$store.commit('removeTask', index) } } } </script>
Here, we use a computed attribute to obtain the tasks array status in the store. We also use the v-for directive in the template to display each task and add a delete button after each task. When the user clicks a delete button, we call the removeTask method and pass the task's index as a parameter to the $store.commit method. This triggers the removeTask mutation we defined previously, which removes the task from the store.
Conclusion
In this article, we learned how to use Vuex to manage the global state of our application and demonstrated how to actually use it in a Vue project through a ToDo List application it. In a Vue project, using Vuex allows us to manage and share state more easily, and makes our code more modular and readable. If you are also developing a Vue project, you may wish to consider using Vuex to better manage the state of your application!
The above is the detailed content of Practical sharing on using vuex to manage global status in Vue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.
