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.
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('increment', 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 的重点是通常在大型应用程序中创建可扩展的全局状态。 但是,我们可以在一个简单的待办应用程序中演示其功能。
完成后效果如下所示:
现在,删除 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
的名称,其次是我们要传递的对象,是一个新的待办事项(由id
和task
值组成)。
// 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
,它返回未过滤的状态。 在许多情况下,可以使用filter
或map
来转换此内容。
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
For more programming-related knowledge, please visit:##English Original address: https://vuejsdevelopers.com/2017/05/15/vue-js-what-is-vuex/
Author: Anthony GoreReprint address: https ://segmentfault.com/a/1190000039872016
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!

VueUse 是 Anthony Fu 的一个开源项目,它为 Vue 开发人员提供了大量适用于 Vue 2 和 Vue 3 的基本 Composition API 实用程序函数。本篇文章就来给大家分享几个我常用的几个 VueUse 最佳组合,希望对大家有所帮助!

Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

如何使用VueRouter4.x?下面本篇文章就来给大家分享快速上手教程,介绍一下10分钟快速上手VueRouter4.x的方法,希望对大家有所帮助!

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

本篇文章给大家整理分享8个GitHub上很棒的的 Vue 项目,都是非常棒的项目,希望当中有您想要收藏的那一个。

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!


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

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.