Vuex原理:通過Vuex實(shí)現(xiàn)TodoList
什么是Vuex
「Vuex」 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它可以集中管理應(yīng)用中的組件共享狀態(tài),并提供一些工具來保持狀態(tài)的一致性。Vuex 主要用于解決以下問題:
- 「組件通信」:在大型的 Vue.js 應(yīng)用中,多個(gè)組件可能需要共享一些狀態(tài)(數(shù)據(jù))。而通過簡單的組件通信方式(props、自定義事件)在復(fù)雜的組件關(guān)系中可能會(huì)變得不夠靈活或繁瑣。
- 「狀態(tài)管理」:Vue.js 的單向數(shù)據(jù)流通過 props 將數(shù)據(jù)從父組件傳遞給子組件,但對(duì)于多層嵌套的組件結(jié)構(gòu),數(shù)據(jù)流管理可能變得復(fù)雜。Vuex 提供了一種集中式管理狀態(tài)的方式,使得狀態(tài)的變更變得可預(yù)測(cè)且易于調(diào)試。
以下是 Vuex 的核心概念:
1. 「State(狀態(tài))」
Vuex 使用一個(gè)包含應(yīng)用層級(jí)狀態(tài)的對(duì)象,即 State。這個(gè)狀態(tài)是響應(yīng)式的,當(dāng)狀態(tài)發(fā)生變化時(shí),相關(guān)組件將自動(dòng)更新。
const store = new Vuex.Store({
state: {
count: 0
}
});
2. 「Mutations(變更)」
狀態(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++;
}
}
});
3. 「Actions(動(dòng)作)」
Actions 是用于提交 Mutations 的函數(shù),可以包含異步操作。通過 Actions,可以更靈活地處理業(yè)務(wù)邏輯,例如異步請(qǐng)求或條件判斷。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
}
});
4. 「Getters(獲取器)」
Getters 允許組件在訪問狀態(tài)時(shí)進(jìn)行計(jì)算,類似于 Vue 組件中的計(jì)算屬性。Getters 的結(jié)果會(huì)被緩存,只有依賴的狀態(tài)發(fā)生變化時(shí)才會(huì)重新計(jì)算。
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
doubleCount: state => state.count * 2
}
});
5. 「Modules(模塊)」
Vuex 允許將 Store 分割成模塊,每個(gè)模塊擁有自己的 state、mutations、actions、getters。這樣可以更好地組織大型的 Store。
const moduleA = {
state: { /* ... */ },
mutations: { /* ... */ },
actions: { /* ... */ },
getters: { /* ... */ }
};
const store = new Vuex.Store({
modules: {
a: moduleA
}
});
6. 單一狀態(tài)樹
Vuex 使用一個(gè)單一的狀態(tài)樹來管理應(yīng)用中的所有狀態(tài)。這使得整個(gè)應(yīng)用的狀態(tài)變化可追蹤和調(diào)試。
7. Plugin(插件)
Vuex 允許通過插件擴(kuò)展其功能。插件是一個(gè)函數(shù),可以在每次 mutation 發(fā)生時(shí)執(zhí)行一些自定義的邏輯,例如記錄日志或持久化存儲(chǔ)。
// Vuex 插件示例
const myPlugin = store => {
// 每次 mutation 時(shí)調(diào)用
store.subscribe((mutation, state) => {
console.log('mutation type:', mutation.type);
});
};
8. 嚴(yán)格模式
Vuex 提供了嚴(yán)格模式,用于檢測(cè) 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 不是必需的,尤其對(duì)于小型應(yīng)用可能會(huì)顯得繁瑣,但在大型、復(fù)雜的應(yīng)用中,它提供了一種有組織的方法來管理狀態(tài)。
利用Vuex實(shí)現(xiàn)一個(gè)tudoList
簡單了解一下Vuex之后呢,實(shí)現(xiàn)一個(gè)小案例。下面是一個(gè)使用 Vue 3 和 Vuex 的簡單的 Todo List 示例。使用前需要先下載依賴。這個(gè)應(yīng)該都會(huì)吧。創(chuàng)建一個(gè) store 文件夾,并在其中創(chuàng)建 index.js 文件來定義 Vuex 的 store:
// store/index.js
import { 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 文件中使用這個(gè) 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>
這個(gè)示例中,我們使用 Vuex 來管理 todo 列表的狀態(tài),包括添加新 todo、切換 todo 狀態(tài)、刪除 todo 等功能。在模板中,我們使用了 v-for 指令來渲染 todo 列表,并通過 Vuex 的 getters 計(jì)算屬性顯示已完成和未完成的 todo 列表。
小結(jié)
使用vuex能夠?qū)崿F(xiàn)組件之間的通信,它是一個(gè)狀態(tài)管理機(jī)制,集中管理組件共享狀態(tài)。