「Vuex」 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它可以集中管理應(yīng)用中的組件共享狀態(tài),并提供一些工具來保持狀態(tài)的一致性。Vuex 主要用于解決以下問題:
以下是 Vuex 的核心概念:
Vuex 使用一個包含應(yīng)用層級狀態(tài)的對象,即 State。這個狀態(tài)是響應(yīng)式的,當(dāng)狀態(tài)發(fā)生變化時(shí),相關(guān)組件將自動更新。
const store = new Vuex.Store({ state: { count: 0 }});
狀態(tài)的變更必須通過 Mutations 來進(jìn)行。Mutations 是同步函數(shù),用于修改狀態(tài)。通過這種方式,可以追蹤狀態(tài)的變更,并且可以實(shí)現(xiàn)一些限制條件,確保狀態(tài)的可控性。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }});
Actions 是用于提交 Mutations 的函數(shù),可以包含異步操作。通過 Actions,可以更靈活地處理業(yè)務(wù)邏輯,例如異步請求或條件判斷。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment'); }, 1000); } }});
Getters 允許組件在訪問狀態(tài)時(shí)進(jìn)行計(jì)算,類似于 Vue 組件中的計(jì)算屬性。Getters 的結(jié)果會被緩存,只有依賴的狀態(tài)發(fā)生變化時(shí)才會重新計(jì)算。
const store = new Vuex.Store({ state: { count: 0 }, getters: { doubleCount: state => state.count * 2 }});
Vuex 允許將 Store 分割成模塊,每個模塊擁有自己的 state、mutations、actions、getters。這樣可以更好地組織大型的 Store。
const moduleA = { state: { /* ... */ }, mutations: { /* ... */ }, actions: { /* ... */ }, getters: { /* ... */ }};const store = new Vuex.Store({ modules: { a: moduleA }});
Vuex 使用一個單一的狀態(tài)樹來管理應(yīng)用中的所有狀態(tài)。這使得整個應(yīng)用的狀態(tài)變化可追蹤和調(diào)試。
Vuex 允許通過插件擴(kuò)展其功能。插件是一個函數(shù),可以在每次 mutation 發(fā)生時(shí)執(zhí)行一些自定義的邏輯,例如記錄日志或持久化存儲。
// Vuex 插件示例const myPlugin = store => { // 每次 mutation 時(shí)調(diào)用 store.subscribe((mutation, state) => { console.log('mutation type:', mutation.type); });};
Vuex 提供了嚴(yán)格模式,用于檢測 State 的變更是否是通過 Mutations 進(jìn)行的。在開發(fā)環(huán)境中啟用嚴(yán)格模式可以幫助捕獲不合規(guī)的狀態(tài)變更。
const store = new Vuex.Store({ // ... strict: process.env.NODE_ENV !== 'production'});
通過這些概念,Vuex 提供了一種集中式狀態(tài)管理的解決方案,使得狀態(tài)在應(yīng)用中的傳遞和管理更為清晰和可維護(hù)。Vuex 不是必需的,尤其對于小型應(yīng)用可能會顯得繁瑣,但在大型、復(fù)雜的應(yīng)用中,它提供了一種有組織的方法來管理狀態(tài)。
簡單了解一下Vuex之后呢,實(shí)現(xiàn)一個小案例。下面是一個使用 Vue 3 和 Vuex 的簡單的 Todo List 示例。使用前需要先下載依賴。這個應(yīng)該都會吧。創(chuàng)建一個 store 文件夾,并在其中創(chuàng)建 index.js 文件來定義 Vuex 的 store:
// store/index.jsimport { createStore } from 'vuex';export default createStore({ state: { todos: [] }, mutations: { addTodo(state, todo) { state.todos.push(todo); }, toggleTodo(state, index) { state.todos[index].completed = !state.todos[index].completed; }, removeTodo(state, index) { state.todos.splice(index, 1); } }, actions: { addTodoAsync({ commit }, todo) { setTimeout(() => { commit('addTodo', todo); }, 1000); } }, getters: { completedTodos: state => state.todos.filter(todo => todo.completed), remainingTodos: state => state.todos.filter(todo => !todo.completed) }});
然后在 App.vue 文件中使用這個 store:
// App.vue<template> <div id="app"> <h1>Todo List</h1> <form @submit.prevent="addTodo"> <input v-model="newTodo" placeholder="Add a new todo" /> <button type="submit">Add</button> </form> <div> <h2>Todo Items</h2> <ul> <li v-for="(todo, index) in todos" :key="index"> <input type="checkbox" v-model="todo.completed" /> {{ todo.text }} <button @click="removeTodo(index)">Remove</button> </li> </ul> </div> <div> <h2>Completed Todos</h2> <ul> <li v-for="(todo, index) in completedTodos" :key="index"> {{ todo.text }} </li> </ul> </div> <div> <h2>Remaining Todos</h2> <ul> <li v-for="(todo, index) in remainingTodos" :key="index"> {{ todo.text }} </li> </ul> </div> </div></template><script>import { computed } from 'vue';import { useStore } from 'vuex';export default { name: 'App', data() { return { newTodo: '' }; }, methods: { addTodo() { this.$store.commit('addTodo', { text: this.newTodo, completed: false }); this.newTodo = ''; }, removeTodo(index) { this.$store.commit('removeTodo', index); } }, computed: { todos() { return this.$store.state.todos; }, completedTodos: computed(() => useStore().getters.completedTodos), remainingTodos: computed(() => useStore().getters.remainingTodos) }};</script><style>#app { font-family: Avenir, Helvetica, Arial, sans-serif; text-align: center; color: #2c3e50; margin-top: 60px;}form { margin-bottom: 20px;}ul { list-style-type: none; padding: 0;}li { margin-bottom: 5px;}</style>
這個示例中,我們使用 Vuex 來管理 todo 列表的狀態(tài),包括添加新 todo、切換 todo 狀態(tài)、刪除 todo 等功能。在模板中,我們使用了 v-for 指令來渲染 todo 列表,并通過 Vuex 的 getters 計(jì)算屬性顯示已完成和未完成的 todo 列表。
使用vuex能夠?qū)崿F(xiàn)組件之間的通信,它是一個狀態(tài)管理機(jī)制,集中管理組件共享狀態(tài)。
本文鏈接:http://www.tebozhan.com/showinfo-26-112757-0.htmlVuex原理:通過Vuex實(shí)現(xiàn)TodoList
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com