Skip to content

Vuex

1.作用

Vuex是一个状态管理工具,可以理解为一个公告的仓库,适用于任意组件之间的通信

2.使用

2.1 下载

bash
npm i vuex@3
  • 注意**:Vue2 安装 Vuex3,Vue3 安装 Vuex4,版本需对应。**

2.2 创建store

store即我们的仓库

src/store/index.js

js
import Vue from 'vue'
import Vuex from 'vuex'	// 引入Vuex

Vue.use(Vuex)	// 应用Vuex插件

const state = {	
    键:值
}			
const getters = {
    函数名(state){
        return xxx
    }
}
const mutations = {
    函数名(state,payload){}
}	   
const actions = {
    函数名(context,payload)
}


export default new Vuex.Store({    // 创建并暴露store
    state,
    getters,
	actions,
	mutations,
})

2.3 注册store

main.js

js
import store from './store'	// 引入store

new Vue({
	store,			// 配置项添加store
    //...
})

3.Vuex核心配置项

Vuex的配置项都是以对象的形式存在,可以在这些配置项中做相应的操作

3.1 state

3.1.1 作用

state用来定义数据

3.1.2 定义

js
export default new Vuex.Store({    // 创建并暴露store
    state:{
        key:value,
		key1:value2,
        //...
    }
    //...
})

3.1.3 使用

vue
// 视图中
<p>{{ $store.state.key }}</p>
<p>{{ $store.state.key2 }}</p>


// 模型中
this.$store.state.key
this.$store.state.key2

3.2 getters

3.2.1 作用

  • 当 state 中的数据需要经过加工后再使用时,可以使用 getters 加工
  • 它不是必须的,当加工逻辑复杂且需要复用时,可以考虑使用
  • state 与 getters 的关系有点像 data 和 computed 的关系

3.2.2 定义

getters的定义相当于组件中computed的定义

  • 定义的方式为函数
  • 必须要有返回值
  • 函数有一个形参state,可以通过state.key的方式获取此仓库的数据
js
export default new Vuex.Store({    // 创建并暴露store
    getters:{
        函数名(state){                //传入state
            return xxx   			 // 返回值
        }
        //...
    }
    //...
})

3.2.3 使用

使用不需要加()

vue
// 视图中
<h1>{{ $store.getters.函数名 }}</h1>

// 模型中
this.$store.getters.函数名

3.3 actions

3.3.1 作用

  • 主要通过异步操作获取接口数据

3.3.2 定义

  • actions中定义一个个方法,用于异步操作
  • action中的函数有两个参数contextpayload
    • context:是一个迷你版的 store,可通过context.key的方式访问仓库中的数据和方法
      • 访问state中数据:context.state.key
      • 访问mutations中方法:context.commit(FnName,value)
        • FnName:mutations中的方法名,类型为String
        • value:传递的参数
      • 访问actions中方法:context.dispatch()
    • payload:调用方法时传过来的实参
js
export default new Vuex.Store({    // 创建并暴露store
    actions: {
        eventName(context,payload){
            context.commit('MuFnName',value)   //把数据交给mutations中的MuFnName方法梳理
        },
        eventName2(context,payload){
            console.log(11111)
        }
        //...
     }
     //...
})

3.3.3 使用

通过$store.dispatch('AcFnName',payload)

  • AcFnName中的回调函数
  • payload传出去的值,需要传输多个数据把payload写成对象
js
//视图中
<button @click="$store.dispatch('AcFnName',payload)"></button>


//模型中
methods:{
    incrementOdd() {
        this.$store.dispatch('AcFnName',payload)
    }
}

3.4 mutations

3.4.1 作用

  • 值为一个对象,包含多个直接更新 state中数据方法
  • 不能写异步代码,只能单纯地操作 state

3.4.2 定义

mutations中的方法有两个形参,state,payload

  • state:store中的state
  • payload:传过来的参数
js
export default new Vuex.Store({    // 创建并暴露store
    mutations: {
            MuFnName(state,payload){
                
            },
        //...
     }
     //...
})

3.4.3 使用

通过commit('MuFnName',payload)

  • MuFnNamemutations里的回调函数
  • payload:传出去的值
js
// 视图中调用
<button @click="$store.commit('AcFnName',payload)"></button>

// 模型中调用
methods:{
    increment() {
        this.$store.commit('AcFnName',payload)
    }
}

4.辅助函数

辅助函数可以方便我们使用仓库里的数据

一共有四个:mapStatemapGettersmapActionsmapMutations

使用前需引入:

js
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'

4.1 mapState/mapGetters

4.1.1 作用

  • mapState用于帮助映射state中的数据为计算属性
  • mapGetters用于帮助映射getters中的数据为计算属性
  • 两者都需要通过解构赋值的方式使用在computed配置项中

4.1.2 语法

1.定义数据

store.js

js
export default new Vuex.Store({    
    state:{
        key1:value1,
        key2:value2
    },
    getters:{
        Cp(state){
            return xxx
        }
    }
    //...
})

2.组件中获取数据

js
computed: {
    // 获取state
    
    // 借助mapState生成计算属性:sum、school、subject(数组写法)
  	...mapState(['key1','key2']),
        
  	// 借助mapState生成计算属性:sum、school、subject(对象写法)
    // 对象写法可以给数据起别名,避免数据名冲突
  	...mapState({
        value1:state => state.key1,
        value2:state => state.key2, 
    }),

  	

    // 获取getters   
         
    // 借助mapGetters生成计算属性:bigSum(数组写法)
    ...mapGetters(['Cp'])
    
    // 借助mapGetters生成计算属性:bigSum(对象写法)
    ...mapGetters({
        Cp:'Cp'
    }),
}

3.使用数据

vue
<h1>{{key1}}</h1>
<h1>{{value1}},{{value2}}</h1>

<h1>{{Cp}}</h1>

4.2 mapActions/mapMutations

4.2.1 作用

  1. mapActions用于帮助生成与actions对话的方法,即包含$store.dispatch(xxx)的函数
  2. mapMutations用于帮助生成与mutations对话的方法,即包含$store.commit(xxx)的函数

在组件中配置methods配置项

使用解构赋值,mapActionsmapMutations写在里面

4.2.2 语法

1.store中定义方法

store.js

js
export default new Vuex.Store({    
    actions:{
        actionFn(context,payload){
            //...
        },
        actionFn1(context,payload){
            //...
        },
    },
    mutations:{
        mutationsFn(state,payload){
            //...
        },
        mutationsFn1(state,payload){
            //...
        }
    }
})

2.获取

js
methods:{
    //靠mapActions生成:incrementOdd、incrementWait(数组形式)
    ...mapActions(['actionFn','actionFn1'])
    
    //靠mapActions生成:incrementOdd、incrementWait(对象形式),可以起别名
    ...mapActions({
        aFn:'actionFn',
        aFn1:'actionFn1'
    })

    
    
    //靠mapMutations生成:JIA、JIAN(数组形式)
    ...mapMutations(['mutationsFn','mutationsFn1']),

    //靠mapMutations生成:increment、decrement(对象形式),可以起别名
    ...mapMutations({
        mFn:'mutationsFn',
        mFn1:'mutationsFn1'
    }),
}

注意:mapActionsmapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象

5.Vuex模块化

5.1 作用

实际开发中,公共数据太多,可以将Vuex分成一个个模块

5.2 语法

注意事项:

  • 每一个小模块都要通过namespaced:true配置项开启命名空间
  • 最后将小模块放入storemodules配置项中

5.2.1 定义模块数据

js
// 模块一
const mod1 = {
  namespaced: true,
  state: {},
  mutations: {},
  actions: {},
  getters: {}
}

// 模块二
const mod2 = {
  namespaced: true,	
  state: {},
  getters: {},
  mutations: {},
  actions: {}
}

const store = new Vuex.Store({
  //公共数据
  state:{},
  getters:{},
  mutations:{}.
  actions:{}
    
  //模块数据
  modules: {
    mod1,
    mod2
  }
})

5.2.2 使用模块数据

1.开启命名空间后,组件中读取state数据

js
// 方式一:自己直接读取
this.$store.state.mod1.键

//方式二:mapState对象
...mapState({
   // 公共数据
   自定义键:state=>state.键,
   // 模块数据
   自定义键:state=>state.mod1.键
})

2.开启命名空间后,组件中读取getters数据

js
//方式一:自己直接读取
this.$store.getters['mod1/firstPersonName']
//方式二:借助mapGetters读取:
...mapGetters({
   //公共数据
   方法名: '方法名',
   //模块数据
   方法名: '模块名/方法名',
})

3.开启命名空间后,组件中调用actions中方法

js
//方式一:自己直接dispatch
this.$store.dispatch('mod1/fn1',value)
//方式二:借助mapActions:
...mapActions('mod1',{
    fn1Changed:'fn1',
    fn2Changed:'fn2'
})
//或者
...mapMutations({
 	方法名: '模块名/方法名'
 	//...
})

4.开启命名空间后,组件中调用commit

js
//方式一:自己直接commit
this.$store.commit('mod2/fnn1',value1)
//方式二:借助mapMutations:
...mapMutations('mod2',{
    fnn1Changed:'fnn1',
    fnn1Changed:'fnn2'
}),
// 或者
...mapActions({
 	方法名: '模块名/方法名'
 	//...
})

6.注意事项

1.数据持久化

使用Vuex中的数据时,刷新数据数据会消失

通过存储localStorage的方法实现数据持久化

MIT Licensed