search
HomeWeb Front-endVue.jsWhat is Vuex? Beginner's Guide to Vuex 4

This article takes you through Vuex and introduces how to use Vuex in applications. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

What is Vuex? Beginner's Guide to Vuex 4

Vuex is an essential tool in the Vue.js ecosystem. But developers new to Vuex may be put off by terms like "state management pattern" and confused as to what they actually need Vuex for. [Related recommendations: "vue.js Tutorial"]

This article is an introduction to Vuex. Of course, it will also cover the advanced concepts of Vuex and show you how to use Vuex in applications.

The problems Vuex solves

To understand Vuex, you must first understand the problems it solves.

Suppose we develop a multi-user chat application. The interface has a user list, a private chat window, an inbox with chat history, and a notification bar that notifies the user of unread messages from other users that are not currently being viewed.

Millions of users chat with millions of other users through our app every day. However, some people have complained about an annoying issue: the notification shade occasionally gives false notifications. Users are notified of a new unread message, but when they view it, it's just a message that has already been viewed.

What this author is describing is a real-life situation that Facebook developers encountered in their chat system a few years ago. In solving this problem, developers created an application architecture called "Flux". Flux forms the basis for Vuex, Redux and other similar libraries.

Flux

Facebook developers have been struggling with the problem of “zombie notifications” for some time. They eventually realized that its persistence was more than a simple flaw - it pointed to some underlying flaw in the application's architecture.

The flaw is easiest to understand in the abstract: when there are multiple components in an application that share data, the complexity of their interconnections increases to the point where the state of the data cannot be predicted or understood. Therefore, the application cannot be expanded or maintained.

Flux is a pattern, not a library. We cannot go to Github to download Flux. It is a design pattern similar to MVC. Libraries like Vuex and Redux implement the Flux pattern the same way other frameworks implement the MVC pattern.

In fact, Vuex does not implement all of Flux, only a subset. But don't worry about that now, let's focus on understanding the key principles it follows.

Principle 1: Single Source

Components may have local data that only needs to be understood. For example, the position of the scroll bar in a user list component may be independent of other components.

However, any data that is to be shared between components (i.e. application data) must be kept in a separate location, separate from the components that use it.

This single location is called "store". The component must read application data from this location and cannot keep its own copy to prevent conflicts or divergences.

import { createStore } from "vuex";

// Instantiate our Vuex store
const store = createStore({

  // "State" 组件的应用程序数据
  
  state () {
    return {
      myValue: 0
    };
  }
});

// 组件从其计算的属性访问 state 
const MyComponent = {   
  template: "<div>{{ myValue }}</div>",
  computed: {
    myValue () {
      return store.state.myValue;
    }   
  } 
};

Principle 2: Data is read-only

Components can freely read data from store. But the data in store cannot be changed, at least not directly.

Instead, they must inform store of the intention to change the data, which store is responsible for passing through a defined set of functions called mutation) to make changes.

Why use this method? If we centralize the data change logic, then if the status is inconsistent, we only need to check it in the same place, without going to each specific file. We minimize the possibility of some random component (perhaps in a third-party module) changing data in unexpected ways.

const store = createStore({ 
  state() { 
    return {
      myValue: 0
    };
  }, 
  mutations: { 
    increment (state, value) { 
      state.myValue += value;
    }
  } 
});
// 需要更新值吗?
// 错误的,不要直接更改 store 值
store.myValue += 10;
// 正确的,调用正确的 mutations。
store.commit(&#39;increment&#39;, 10);

Principle 3: Mutation is synchronous

If the application implements the above two principles in its architecture, debugging data inconsistencies is much easier. You can log commits and watch how the state changes (this is indeed possible when using Vue Devtools).

But if our mutation is called asynchronously, this ability will be weakened. We know the order of submissions, but we don't know the order in which components submit them.

Synchronizationmutation ensures that state does not depend on the order and timing of unpredictable events.

So cool, so what exactly is Vuex?

With all this background knowledge, we can finally solve the problem - Vuex is a library that helps us implement Flux architecture in Vue applications. By enforcing the above principles, Vuex keeps our application data in a transparent and predictable state, even when data is shared between multiple components.

Now that we have a high-level understanding of Vuex, let's look at how to create Vuex-based applications in actual projects.

Make a to-do-list using Vuex

To demonstrate the use of Vuex, we set up a simple to-do application. You can access working examples of the code here.

示例地址:https://codesandbox.io/s/happ...

如果大家自己的电脑尝试一波,那么可以使用下面的命令:

vue create vuex-example

安装 Vuex

cd vuex-example
npm i -S vuex@4
npm run serve

创建一个 Vuex store

现在,创建 Vuex store,在项目中创建 src/store/index.js

mkdir src/store
touch src/store/index.js

打开文件并导入createStore方法。此方法用于定义store及其特性。现在,我们导出该store ,以便在Vue应用中能访问它。

// src/store/index.js

import { createStore } from "vuex";

export default createStore({});

将 store  添加到 Vue 实例

为了可以从任何组件中访问 Vuex store,我们需要在主文件中导入 store 模块,并将store作为插件安装在主Vue实例上

// src/main.js

import { createApp } from "vue";
import App from "@/App";
import store from "@/store";

const app = createApp(App);

app.use(store);

app.mount("#app");

创建一个简单的应用程序

如上所述,Vuex 的重点是通常在大型应用程序中创建可扩展的全局状态。 但是,我们可以在一个简单的待办应用程序中演示其功能。

完成后效果如下所示:

What is Vuex? Beginners Guide to Vuex 4

现在,删除 HelloWorld 文件:

rm src/components/HelloWorld.vue

TodoNew.vue

现在,添加一个新组件 TodoNew,它负责创建新的待办事项。

touch src/components/TodoNew.vue

打开 TodoNew.vue 并输入以下内容:

// src/components/TodoNew.vue

<template>
  <form @submit.prevent="addTodo">
    <input
      type="text"
      placeholder="Enter a new task"
      v-model="task"
    />
  </form>
</template>

现在转到组件定义,有两个局部状态属性-task和给新待办事项提供唯一标识符的id

// src/components/TodoNew.vue

<template>...</template>
<script>
export default {
  data() {
    return {
      task: "",
      id: 0
    };
  },
  methods: {
    addTodo: function() {
      //
    }
  }
};
</script>

定义 store 状态

过会,我们会创建一个显示待办事项的组件。 由于它和TodoNew组件都需要访问相同的数据,因此这是我们在 Vuex 存储中保存的全局state 的理想选择。

现在,回到state并定义属性状态。 这里使用 Vux4 提供的 createStore 函数,该函数返回一个对象。 该对象具有一个属性 todos,它是一个空数组。

// src/store/index.js
import { createStore } from "vuex";

export default createStore({
  state () {
    return {
      todos: []
    }
  }
});

定义 mutation

从原则2可以知道,Vuex state 不能直接更改,需要定义mutator函数。

现在,我们向store添加一个mutation属性,并添加一个函数属性addTodo。 所有mutator方法第一个参数。 第二个可选参数是 store,第二个是传递的数据。

// src/store/index.js

import { createStore } from "vuex";

export default createStore({
  state () {
    return {
      todos: []
    }
  },
  mutations: {
    addTodo (state, item) {
      state.todos.unshift(item);
    }
  }
});

使用 commit 调用 mutation

现在,可以在TodoNew组件中使用它,在 TodoNew组件定义一个addTodo方法。

要访问store ,我们可以使用全局属性this.$store。 使用commit方法创建一个新的mutation。 需要传递了两个参数-首先是mutation的名称,其次是我们要传递的对象,是一个新的待办事项(由idtask值组成)。

// src/components/TodoNew.vue
methods: {
  addTodo: function() {
    const { id, task } = this;
    this.$store.commit("addTodo", { id, task });
    this.id++;
    this.task = "";
  }
}

回顾

到目前为止:

  • 用户将待办事项通过输入框输入,并绑定到 task 变量。

  • 提交表单后,将调用addTodo方法

  • 创建一个待办事项对象并将其“提交”到store中。

// src/components/TodoNew.vue
<template>
  <form @submit.prevent="addTodo">
    <input
      type="text"
      placeholder="Enter a new task"
      v-model="task"
    />
  </form>
</template>
<script>
export default {
  data() {
    return {
      task: "",
      id: 0
    };
  },
  methods: {
    addTodo: function() {
      const { id, task } = this;
      this.$store.commit("addTodo", { id, task });
      this.id++;
      this.task = "";
    }
  }
};
</script>

读取 store 数据

现在,我们已经创建了用于添加待办事项的功能。 接下来,就是把它们显示出来。

创建一个新组件TodoList.vue 文件。

touch src/components/TodoList.vue

内容如下:

// src/components/TodoList.vue
<template>
<ul>
  <li
    v-for="todo in todos"
    :key="todo.id"
  >
    {{ todo.description }}
  </li>
</ul>
</template>

todos是一个计算属性,我们在其中返回Vuex store 的内容。

// src/components/TodoList.vue

<script>
export default {
  computed: {
    todos() {
      // 
    }
  }
};
</script>

定义 getters

与直接访问store 内容不同,getter是类似于存储的计算属性的函数。在将数据返回到应用程序之前,这些工具非常适合过滤或转换数据。

例如,下面有getTodos,它返回未过滤的状态。 在许多情况下,可以使用filtermap来转换此内容。

todoCount返回todo数组的长度。

通过确保组件愿意保留数据的本地副本,getter有助于实现原则1,即单一数据来源。

// src/store/index.js

export default createStore({
  ...
  getters: {
    getTodos (state) {
      return state.todos;
    },
    todoCount (state) {
      return state.todos.length;
    }
  }
})

返回TodoList组件,我们通过返回this.$store.getters.getTodos来完成功能。

// src/components/TodoList.vue

<script>
export default {
  computed: {
    todos() {
      return this.$store.getters.getTodos;
    }
  }
};
</script>

App.vue

要完成此应用程序,现在要做的就是导入并在App.vue中声明我们的组件。

// src/App.vue

<template>
  <p>
    <h1 id="To-Do-nbsp-List">To-Do List</h1>
    <p>
      <TodoNew />
      <TodoList />
    </p>
  </p>
</template>
<script>
import TodoNew from "@/components/TodoNew.vue";
import TodoList from "@/components/TodoList.vue";

export default {
  components: {
    TodoNew,
    TodoList
  }
};
</script>

你真的需要Vuex吗?

显然,在大型应用程序中,拥有全局状态管理解决方案将有助于让我们的应用程序可预测和可维护。

But for relatively small projects, sometimes I feel that using Vuex is overkill, and it is more reasonable for everyone to follow the actual needs.

Advantages of Vuex:

  • Easy to manage global state
  • Powerful debugging global state

Disadvantages of Vuex:

  • Additional project dependencies
  • Complicated templates

##English Original address: https://vuejsdevelopers.com/2017/05/15/vue-js-what-is-vuex/

Author: Anthony Gore

Reprint address: https ://segmentfault.com/a/1190000039872016

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of What is Vuex? Beginner's Guide to Vuex 4. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js vs. React: Which Framework is Right for You?Vue.js vs. React: Which Framework is Right for You?May 01, 2025 am 12:21 AM

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js vs. React: A Comparative Analysis of JavaScript FrameworksVue.js vs. React: A Comparative Analysis of JavaScript FrameworksApr 30, 2025 am 12:10 AM

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js vs. React: Use Cases and ApplicationsVue.js vs. React: Use Cases and ApplicationsApr 29, 2025 am 12:36 AM

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

Vue.js vs. React: Comparing Performance and EfficiencyVue.js vs. React: Comparing Performance and EfficiencyApr 28, 2025 am 12:12 AM

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool