Home > Article > Web Front-end > 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.
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.
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.
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; } } };
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);
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.
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.
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
cd vuex-example npm i -S vuex@4 npm run serve
现在,创建 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({});
为了可以从任何组件中访问 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
,它负责创建新的待办事项。
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>
过会,我们会创建一个显示待办事项的组件。 由于它和TodoNew
组件都需要访问相同的数据,因此这是我们在 Vuex 存储中保存的全局state
的理想选择。
现在,回到state
并定义属性状态。 这里使用 Vux4 提供的 createStore
函数,该函数返回一个对象。 该对象具有一个属性 todos
,它是一个空数组。
// src/store/index.js import { createStore } from "vuex"; export default createStore({ state () { return { todos: [] } } });
从原则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); } } });
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>
现在,我们已经创建了用于添加待办事项的功能。 接下来,就是把它们显示出来。
创建一个新组件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>
与直接访问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>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>
显然,在大型应用程序中,拥有全局状态管理解决方案将有助于让我们的应用程序可预测和可维护。
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:
Disadvantages of Vuex:
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!