Table of Contents
What is Vuex?
Use Vuex in the Vue project
Conclusion
Home Web Front-end Vue.js Practical sharing on using vuex to manage global status in Vue

Practical sharing on using vuex to manage global status in Vue

Jun 09, 2023 pm 04:10 PM
vue vuex Status management

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')
Copy after login

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>
Copy after login

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>
Copy after login

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

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.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

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

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

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.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

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.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

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

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

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 &lt;div&gt;. 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.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

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.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

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 &lt;script&gt; tag in the HTML file that refers to the Vue file.

See all articles