「Vuex」 是一個專為 Vue.js 應用程序開發的狀態管理模式。它可以集中管理應用中的組件共享狀態,并提供一些工具來保持狀態的一致性。Vuex 主要用于解決以下問題:
以下是 Vuex 的核心概念:
Vuex 使用一個包含應用層級狀態的對象,即 State。這個狀態是響應式的,當狀態發生變化時,相關組件將自動更新。
const store = new Vuex.Store({ state: { count: 0 }});
狀態的變更必須通過 Mutations 來進行。Mutations 是同步函數,用于修改狀態。通過這種方式,可以追蹤狀態的變更,并且可以實現一些限制條件,確保狀態的可控性。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }});
Actions 是用于提交 Mutations 的函數,可以包含異步操作。通過 Actions,可以更靈活地處理業務邏輯,例如異步請求或條件判斷。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment'); }, 1000); } }});
Getters 允許組件在訪問狀態時進行計算,類似于 Vue 組件中的計算屬性。Getters 的結果會被緩存,只有依賴的狀態發生變化時才會重新計算。
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 使用一個單一的狀態樹來管理應用中的所有狀態。這使得整個應用的狀態變化可追蹤和調試。
Vuex 允許通過插件擴展其功能。插件是一個函數,可以在每次 mutation 發生時執行一些自定義的邏輯,例如記錄日志或持久化存儲。
// Vuex 插件示例const myPlugin = store => { // 每次 mutation 時調用 store.subscribe((mutation, state) => { console.log('mutation type:', mutation.type); });};
Vuex 提供了嚴格模式,用于檢測 State 的變更是否是通過 Mutations 進行的。在開發環境中啟用嚴格模式可以幫助捕獲不合規的狀態變更。
const store = new Vuex.Store({ // ... strict: process.env.NODE_ENV !== 'production'});
通過這些概念,Vuex 提供了一種集中式狀態管理的解決方案,使得狀態在應用中的傳遞和管理更為清晰和可維護。Vuex 不是必需的,尤其對于小型應用可能會顯得繁瑣,但在大型、復雜的應用中,它提供了一種有組織的方法來管理狀態。
簡單了解一下Vuex之后呢,實現一個小案例。下面是一個使用 Vue 3 和 Vuex 的簡單的 Todo List 示例。使用前需要先下載依賴。這個應該都會吧。創建一個 store 文件夾,并在其中創建 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 列表的狀態,包括添加新 todo、切換 todo 狀態、刪除 todo 等功能。在模板中,我們使用了 v-for 指令來渲染 todo 列表,并通過 Vuex 的 getters 計算屬性顯示已完成和未完成的 todo 列表。
使用vuex能夠實現組件之間的通信,它是一個狀態管理機制,集中管理組件共享狀態。
本文鏈接:http://www.tebozhan.com/showinfo-26-112757-0.htmlVuex原理:通過Vuex實現TodoList
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: Uniapp 開發神器,效率翻倍!
下一篇: 高性能、無侵入的 Java 性能監控神器