What 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.
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!

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



When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

vscode itself supports Vue file components to jump to definitions, but the support is very weak. Under the configuration of vue-cli, we can write many flexible usages, which can improve our production efficiency. But it is these flexible writing methods that prevent the functions provided by vscode itself from supporting jumping to file definitions. In order to be compatible with these flexible writing methods and improve work efficiency, I wrote a vscode plug-in that supports Vue files to jump to definitions.

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.
