文章目录
一. 什么是Vuex
vuex是一个专门为vue.js设计的集中式状态(数据)管理架构。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
二. Vuex使用场景
vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值(兄弟组件下又有父子组件),或者大型spa单页面框架项目,页面多并且一层嵌套一层的传值,异常麻烦,用vuex来维护共有的状态或数据会更便捷。

注意:由于vuex中的state存放的数据在页面刷新时会丢失,vuex只能用于单个页面中不同组件(例如兄弟组件)的数据流通
优点:
- 能够在Vuex中集中管理共享的数居,易于开发和后期维护
- 能够高效地实现组件之间的数据共享,提高开发效率
- 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
什么样的数据适合存储到Vuex中:
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可。
三. Vuex核心概念
- store:类似容器,包含应用的大部分状态,一个页面只能有一个容器
- State:包含所有应用级别状态的对象
- Getters:在组件内部获取store中状态的函数,类似组件的计算属性computed
- Mutations:唯一修改状态的事件回调函数,默认是同步的,如果要异步就使用Actions
- Actions:包含异步操作、提交mutations改变状态
- Modules:将store分割成不同的模块
四. 引入Vuex
1、安装vuex
npm install vuex --save
2、新建一个store文件夹(这个不是必须的),并在文件夹下新建index.js文件,在文件中引入我们的vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
getters : {
},
modules: {
}
})
3、在main.js 中引入新建的store
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
五. 页面使用
1. State 数据源
State提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。
//创建store数据源,提供唯一公共数据
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
},
actions: {
},
modules: {
}
})
1.1 this.$store.state.全局数据名称 使用 state
使用 state的第一种方式
this.$store.state.全局数据名称
由于在模板字符串中,是不需要写this的,所以直接写this后边的。
<h3>当前最新的count值为:{{$store.state.count}}</h3>
1.2 mapState 映射为计算属性
使用state的第二种方式
import {mapMutations} from 'vuex'
将当前组件需要的全局数据,映射为当前组件的 computed计算属性:
...mapState(['count'])
<!-- 使用: -->
<h3>当前最新的count值为:{{ count }}</h3>
<h3>当前最新的count值为:{{ xCount }}</h3>
//1.导入辅助函数 mapState
import { mapState } from 'vuex'
export default {
data() {
return {}
},
computed: {
// mapState 可以接收数组或对象形式的参数 映射为计算属性,下面分别示例
//2.1 传入数组
...mapState(['count']),
//2.2 对象形式 可以自定义名称
...mapState({
xCount:state => state.count
})
},
}
2. Mutations 变更store中的数据
Mutations用于变更 Store中的数据。
注意:只有 mutations里的函数,才有权利修改 state 的数据
注意:mutations里不能包含异步操作。
①只能通过 mutations变更 Store数据,不可以直接操作 Store中的数据。
②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
//变更状态
state.count++
}
}
})
2.1 this.$store.commit() 触发 mutations
this.$store.commit() 是触发 mutations的第一种方式
handleAdd() {
this.$store.commit('add')
},
2.2 触发 mutations 时传递值
handleAdd(){
this.$store.commit('addN',5)
}
mutations: {
add(state) {
// 变更状态
state.count++
},
addN(state,step){
// 变更状态
state.count += step
}
},
2.3 MapMutations 映射为方法
触发mutations的第二种方式:
1.从vuex中按需导入 mapMutations函数
import {mapMutations} from 'vuex'
2.通过刚才按需导入的 mapMutations函数,映射为当前组件的methods函数。
store.js
mutations: {
add(state) {
// 变更状态
state.count++
},
sub(state) {
state.count--
},
addN(state, step) {
// 变更状态
state.count += step
},
subN(state, step) {
state.count -= step
}
},
组件A
import { mapState,mapMutations } from 'vuex'
methods:{
...mapMutations(['sub','subN']),
decrement(){
// 调用
this.sub()
},
decrementN(){
this.subN(5)
}
}
3. Actions 专门处理异步操作
Actions用于处理异步任务。
如果通过异步操作变更数据,必须通过 Action,而不能使用Mutation,但是在 Action中还是要通过触发Mutation的方式间接变更数据。
注意:在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
3.1 this.$store.dispatch 触发 Actions
store.js
// 定义 Action
const store = new Vuex.store({
// ...省略其他代码
mutations: {
// 只有 mutations中的函数才有权利修改 state。
// 不能在 mutations里执行异步操作。
add(state) {
state.count++
}
},
actions: {
// 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000);
}
},
})
组件A
// 触发 Action
methods:{
handle(){
// 触发 actions 的第一种方式
this.$store.dispatch('addAsync')
}
}
3.2 mapActions 映射为方法
1.从Vuex中按需导入 mapActions 函数。
import {mapActions} from 'vuex'
2.将指定的 actions 函数,映射为当前组件 methods 的方法。
methods:{
...mapActions(['subAsync']),
decrementAsync(){
this.subAsync()
}
}
store.js
actions: {
// 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
subAsync(context){
setTimeout(() => {
context.commit('sub')
}, 1000);
}
}
4. Getter 类似Vue的计算属性
- Getter 不会修改 Store中的原数据,它只起到一个包装器的作用,将Store中的数据加工后输出出来。
- Getter可以对 Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
- Store中数据发生变化, Getter 的数据也会跟着变化。
//定义 Getter
const store = new Vuex.Store({
state:{
count:0
},
getters: {
showNum(state) {
return '当前最新的数量是【' + state.count + '】'
}
},
})
4.1 通过 this.$store.getters.名称 访问
this.$store.getters.名称
4.2 mapGetters 映射为计算属性
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}
5. Modules 模块
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
相对来说 本意就是 能够在大型项目中,更加细化的我们的状态管理,使得结构更加的清晰,当然,也会稍微有点儿复杂
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
this.store.state.a // -> 获得moduleA 的状态
this.store.state.b // -> 获得moduleB 的状态
- 内部state,模块内部的state是局部的,也就是模块私有的,
- 内部getter,mutation,action 仍然注册在全局命名空间内,这样使得多个模块能够对同一 mutation 或 action
作出响应。 - 对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象 state。
- 对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:
- 对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:
const moduleA = {
state: () => ({
count:"",
}),
actions: {
//这里的state为局部状态,rootState为根节点状态
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
mutations: {
// 这里的 `state` 对象是模块的局部状态
increment (state) {
state.count++
}
},
getters: {
//这里的state为局部状态,rootState为根节点状态
doubleCount (state) {
return state.count * 2
},
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}
6. 简写
其实,通过mapState,mapMutations,mapActions,mapGetters映射过来的计算属性,或者方法都可以直接调用,不用在 commit或者 dispatch
如下:
<button @click="decrementAsync">-1Async</button>
import {mapActions} from 'vuex'
//...省略一些代码
methods: {
...mapActions(['subAsync']),
decrementAsync(){
this.subAsync()
}
},
其实可以简写成:
<button @click="subAsync">-1Async</button>
import {mapActions} from 'vuex'
//...省略一些代码
methods: {
...mapActions(['subAsync']),
},
有参数的时候,也可以直接把参数带上,就像这样:
<button @click="subAsync(5)">+5</button>
import {mapActions} from 'vuex'
//...省略一些代码
methods: {
...mapActions(['addAsync']),
},