前言
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
使用
npm install vuex --save
1. 创建 store.js
跟 main.js
平级,新建 sotre.js
文件
// store.js
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({state: {},mutations: {},actions: {}
})
2. 将 store 对象挂载到 vue 实例中
// main.js
import store from './stroe'
new Vue({el: '#app', // 指定要控制的区域render: h => h(app), // 渲染app根组件router, // 挂载路由// 将创建的共享数据对象,挂载到vue实例中// 所有的组件,就可以直接从sotre中获取全局数据了store
})
Vuex 的核心概念
state
state 提供唯一的公共数据源,所有共享的数据都要统一放到 store 的 state 中进行存储
const store = new Vuex.Store({state: {count: 0 // 定义一个全局count},mutations: {},actions: {}
})
组件中访问 state 中数据的第一种方式
// this.$sotre.state.全局数据名称
this.$sotre.state.count
组件中访问 state 中数据的第二种方式
// 1. 从vuex中按需导入mapState函数
impotr { mapState } from 'vuex'
通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:
// 2. 将全局数据,映射为当前组件的计算属性
computed: {...mapState(['count'])
}
// 此时 count 就是当前组件中的一个属性,直接 this.count 就能获取到
mutation
mutation 用于变更 store 中的数据
-
只能通过 mutation 变更 store 数据,不可以直接操作 sotre 中的数据
-
通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
定义 Mutation
const store = new Vuex.Store({state: {count: 0 // 定义一个全局 count},mutations: {add(state) {// 变更状态state.count ++}},actions: {}
})
触发 mutations 的第一种方式
// 组件中使用 mutation
methods: {handler() {// commit 的作用就是调用某个mutation函数this.$sotre.commit('add')}
}
mutation 传参
const store = new Vuex.Store({state: {count: 0 // 定义一个全局 count},mutations: {add(state) {// 变更状态state.count ++},addN(state, step) {// 变更状态state.count += step}},actions: {}
})
methods: {handler() {this.$sotre.commit('addN', 3)}
}
触发 mutations 的第二种方式
// 1. 从 vuex 中按需导入 mapMutations 函数
impotr { mapMutations } from 'vuex'
通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:
// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {...mapMutations(['add', 'addN']),handler1() {this.add()},handler2() {this.addN(3)}
}
注意:mutations 函数中不能写异步代码
const store = new Vuex.Store({state: {count: 0 // 定义一个全局 count},mutations: {add(state) {/* 不要这么写setTimeout(() => {state.count ++}, 1000)*/}},actions: {}
})
action
action 用于处理异步任务。
如果通过异步操作变更数据,必须通过 action,而不能使用 mutation,但是在 action中 还是要通过触发 mutation 的方式间接变更数据。
const store = new Vuex.Store({state: {count: 0 // 定义一个全局 count},// 只有 mutations 中定义的函数,才有权力修改 state 中的数据mutations: {add(state) {// 变更状态state.count ++},addN(state, step) {// 变更状态state.count += step}},actions: {addAsync(context) {setTimeout(() => {// 在 actions 中,不能直接修改 state 中的数据// 必须通过 context.commit() 触发某个 mutation 才行context.commit('add')}, 1000)}}
})
触发 actions 的第一种方式
methods: {handler() {this.$store.dispatch('addAsync')}
}
action 传参
const store = new Vuex.Store({state: {count: 0 // 定义一个全局 count},// 只有 mutations 中定义的函数,才有权力修改 state 中的数据mutations: {add(state) {// 变更状态state.count ++},addN(state, step) {// 变更状态state.count += step}},actions: {addAsync(context) {setTimeout(() => {// 在 actions 中,不能直接修改 state 中的数据// 必须通过 context.commit() 触发某个 mutation 才行context.commit('add')}, 1000)},addNAsync(context, step) {setTimeout(() => {context.commit('addN', step)}, 1000)}}
})
methods: {handler() {this.$store.dispatch('addNAsync', 5)}
}
触发 actions 的第二种方式
// 1. 从 vuex 中按需导入 maoActions函数
import { mapActions } from 'vuex'
通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为档期组件的 methods 方法
// 2. 将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {...mapActions(['addAdync', 'addNAsync'])handler1() {this.addAdync()}// 也可以直接将它作为方法addNAdync() {}
}
注意:mutation 和 action 至多只能传一个参数,如果需要传递多个参数可以包装成对象后再传。
getter
getter 用于对 store 中的数据进行加工处理形成新的数据。
-
getter 可以对 store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。
-
store 中的数据发生变化,getter 的数据也会跟着变化。
// 定义 Getter
const store = new Vuex.Store({state: {count: 0},mutations: { ... },actions: { ... },getters: {// 写法1showNum: state => {return '当前最新的数量是【' + state.count + '】'}// 写法2showNum(state) {return '当前最新的数量是【' + state.count + '】'}}
})
使用 getters 的第一种方式
this.$store.getters.名称
使用 getters 的第二种方式
import { mapGetters } from 'vuex'computed: {...mapGetters(['showNum'])
}
Vue3 中的 Vuex
整体与 Vue2 中的类型,下面给出 Vue3 使用 Vuex 的示例:
1. 创建 Vuex store
import { createStore } from 'vuex';// 创建一个新的store实例
const store = createStore({// 状态,用于存储应用的数据state() {return {count: 0};},// 突变,用于同步修改状态mutations: {add(state) {state.count++;}},// 动作,用于处理异步操作和提交突变actions: {addAsync(context) {setTimeout(() => {context.commit('add');}, 1000);}},// 获取器,用于获取状态的派生数据getters: {showNum(state) {return '当前最新的数量是【' + state.count + '】';}}
});export default store;
2. 挂载
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';const app = createApp(App);
// 使用store
app.use(store);
app.mount('#app');
3. 使用
3.1 使用 useStore
<template><div><p>Count: {{ count }}</p><p>ShowNum: {{ showNum }}</p><button @click="handleAdd">同步添加</button><button @click="handleAddAsync">异步添加</button></div>
</template><script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';// 获取store实例
const store = useStore();// 获取状态
const count = computed(() => store.state.count);
// 获取获取器
const showNum = computed(() => store.getters.showNum);// 提交突变
const handleAdd = () => {store.commit('add');
};// 分发动作
const handleAddAsync = () => {store.dispatch('addAsync');
};
</script>
3.2 使用辅助函数
mapState、mapGetters、mapMutations、mapActions 辅助函数:
<template><div><p>Count: {{ count }}</p><p>ShowNum: {{ showNum }}</p><button @click="handleAdd">同步添加</button><button @click="handleAddAsync">异步添加</button></div>
</template><script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';export default {computed: {...mapState(['count']),...mapGetters(['showNum'])},methods: {// 使用 mapMutations 将 add 方法映射到组件方法...mapMutations(['add']),// 使用 mapActions 将 addAsync 方法映射到组件方法...mapActions(['addAsync']),handleAdd() {this.add();},handleAddAsync() {this.addAsync();}}
};
</script>
还可以更简洁:
<template><div><p>Count: {{ count }}</p><p>ShowNum: {{ showNum }}</p><button @click="add">同步添加</button><button @click="addAsync">异步添加</button></div>
</template><script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';export default {computed: {...mapState(['count']),...mapGetters(['showNum'])},methods: {// 使用 mapMutations 将 add 方法映射到组件方法...mapMutations(['add']),// 使用 mapActions 将 addAsync 方法映射到组件方法...mapActions(['addAsync']),// 当 HTLM 模板中的方法名与 mapMutations 和 mapActions 中映射的方法名相同时可以省略// add() {// this.add();// },// addAsync() {// this.addAsync();// }}
};
</script>
注意:使用 <script setup>
语法糖时不能使用辅助函数,只能使用 useStore。这是因为:
-
首先他们本身就是为选项式 API 设计的辅助函数
-
其次是这些辅助函数,它们依赖于 this 上下文。而
<script setup>
是基于组合式 API 的,没有 this 上下文,因此无法直接使用这些辅助函数。
正是因为 Vuex 对组合式 API 的支持不足,所以才有了与之更适配的 Pinia。
Pinia
官方介绍:相比于 Vuex,Pinia 提供了更简洁直接的 API,并提供了组合式风格的 API,最重要的是,在使用 TypeScript 时它提供了更完善的类型推导。
其他区别:
-
Pinia 简化了状态管理的概念,去掉了 mutations,直接在 actions 中修改 state
-
Pinia 是基于模块化设计的,每个 store 都是独立的,可以轻松地组合和使用
Vuex 模块化
在 Vuex 中,状态管理是通过一个单一的全局状态树实现的。如果你需要将状态拆分成多个模块,必须显式地定义这些模块,并将它们挂载到全局状态树中。
例如:
项目结构:
src/
├── stores/
│ ├── index.js
│ ├── modules/
│ ├── test1.js
│ └── test2.js
├── main.js
└── App.vue
// stores/modules/test1.js
const test1Module = {// 方案二:开启命名空间// namespaced: true,state: () => ({ count1: 0 }),mutations: {add1(state) {state.count1++;},},
};
export default test1Module ;
// stores/modules/test2.js
const test2Module = {// 方案二:开启命名空间// namespaced: true,state: () => ({ count2: 0 }),mutations: {add2(state) {state.count2++;},},
};
export default test2Module ;
// stores/index.js
import { createStore } from 'vuex';
import test1Module from './modules/test1';
import test2Module from './modules/test2';const store = createStore({modules: {test1: test1Module,test2: test2Module}
});export default store;
// mian.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './stores/index.js';const app = createApp(App)
app.use(store);
app.mount('#app')
<template><div><p>Count1: {{ count1 }}</p><p>Count2: {{ count2 }}</p><button @click="add1">add1</button><button @click="add2">add2</button></div>
</template><script>
import { mapState, mapMutations } from 'vuex';export default {computed: {...mapState({count1: state => state.test1.count1,count2: state => state.test2.count2}),},methods: {...mapMutations({// 直接引用 mutation 名add1: 'add1',add2: 'add2'})}/*方案二:开启命名空间写法computed: {...mapState('test1', ['count1']),...mapState('test2', ['count2']),},methods: {...mapMutations('test1', ['add1']),...mapMutations('test2', ['add2']),}*/
};
</script>
Pinia 模块化
例如:
项目结构:
src/
├── stores/
│ ├── index.js
│ ├── modules/
│ ├── test1.js
│ └── test2.js
├── main.js
└── App.vue
// stores/modules/test1.js
import { defineStore } from 'pinia';export const useTest1Store = defineStore('test1', {state: () => ({count1: 0,}),actions: {add1() {this.count1++;},},
});
// stores/modules/test2.js
import { defineStore } from 'pinia';export const useTest2Store = defineStore('test2', {state: () => ({count2: 0,}),actions: {add2() {this.count2++;},},
});
// stores/index.js
import { createPinia } from 'pinia';const pinia = createPinia();
export default pinia;
// mian.js
import { createApp } from 'vue';
import App from './App.vue';
import pinia from './stores'; // 导入 Piniaconst app = createApp(App);
app.use(pinia); // 使用 Pinia
app.mount('#app');
<template><div><p>Count1: {{ count1 }}</p><p>Count2: {{ count2 }}</p><button @click="add1">同步添加</button><button @click="add2">异步添加</button></div>
</template><script setup>
import { useTest1Store } from './stores/modules/test1';
import { useTest2Store } from './stores/modules/test2';
import { storeToRefs } from 'pinia';// 使用 store
const test1Store = useTest1Store();
const test2Store = useTest2Store();// 使结构后依然保持响应性
const { count1 } = storeToRefs(test1Store);
const { count2 } = storeToRefs(test2Store);// 调用 actions
const add1 = () => test1Store.add1();
const add2 = () => test2Store.add2();
</script>