1 什么是vuex
状态管理器,用于存储和管理组件间共享的数据,又称状态机,
是vue全家桶组成部分
2 vuex配置过程
2-1 安装资源
npm i vuex@3.6.2 -S
2-2 创建配置文件src/store/index.js
2-3 编写配置文件index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{},
getters:{},
mutations:{},
actions:{},
modules:{}
})
export default store
2-4 main.js中挂载store到vue实例
import store from './store/index.js'
new Vue({
...,
store,
})
3 vuex的常用5个组成部分
state:{} 用于存储组件间共享的数据,使用的是对象的属性
getters:{}, 用于state中的数据获取或重新加工,类似computed属性
mutations:{},状态唯一的同步修改入口
actions:{},状态的异步修改入口,但是要调用mutations中的方法
modules:{} 对多个状态进行分类,分模块进行管理
4 vuex同步修改状态方法
4-1 组件中
this.$store.commit("updateSync",100)
4-2 vuex配置文件index.js中mutations
updateSync(state,args){
state.num = args
}
5 vuex异步修改状态方法
5-1 组件中
this.$store.dispatch('updateAsync',100)
5-2 vuex配置文件index.js actions中
updateAsync({commit},args){
commit('updateSync',args)
}
-- commit实际就是this.$store.commit
-- updateSync实际就是mutations中定义的函数updateSync
-- args是传递的参数
6 状态的持久方法1
在页面刷新或退出前保存状态到本地存储或数据库,
在页面重新加载时获得数据库或缓存中的状态,
赋值给程序中的状态
6-1 在App.vue中使用生命周期函数created()
6-2 在生命周期函数中判断缓存或数据中是否有存储的状态
created(){
let _state = JSON.parse(localStorage.getItem('store')) // 缓存中的状态
if(_state){
let $state = this.$store.state // 程序中的状态
// 把程序中的状态和缓存的状态合并成一个新的状态对象
let state = Object.assign({},$state,_state)
// 使用最新的状态对象替换程序中原有状态
this.$store.repalceState(state)
}
}
6-3 监听页面的刷新和退出(关闭)执行状态保存到缓存或数据库中
created(){
...
let _this = this
window.addEventListener('beforeunload',()=>{
let state = _this.$store.state
localStorage.setItem('store',JSON.stringify(state))
})
}
7 状态的持久方法2
使用vue-persistedstate插件
7-1 安装插件
npm i vue-persistedstate -S
7-2 在配置文件index.js中引入persistedstate
import {createVuexPersistedState} form 'vue-persistedstate'
7-3 index.js中使用plugins模块
new Vuex.Store({
plugins:[
createVuexPersistedState({
// 缓存的key
key:"你保存缓存时用的key名称",
// 使用的什么缓存
storage:window.localStorage // window.sessionStorage
// 哪些状态要保存--白名单
whiteList:['num','list'], // num list都是state:{num:1,list:[1,2,3],n:20}的属性
// 哪些状态不要保存
blackList:['n']
})
]
})
7-4 持久化操作是在状态被修改后触发保存操作,下次刷新或重新加载,不会丢失状态
8 vuex中modules模块的使用
单一的store状态树,state对象的属性可能会非常多,导致状态臃肿管理不便,可以对状态进行切割封装成单个模块
方便管理状态。每个模块中都有独立的state,getters,mutations,actions
8-1 index.js创建moduleA ,moduleB
const moduleA = {
state: { num: 10 },
getters: {
getNum(state){
return state.num
}
},
mutations: {
addSync(state,args){
state.num = args
}
},
actions: {},
}
const moduleB = {
state: { username: 'admin' },
getters: {},
mutations: {},
actions: {},
}
8-2 修改new Vuex.Store({})
new Vuex.Store({modules:{a:moduleA,b:moduleB}})
8-3 使用模块中的状态
<div> {{$store.state.a.num}},{{$store.state.b.username}} </div>
8-4 修改模块中的状态
组件中使用
this.$store.commit('addSync',100)
8-5 使用模块的getters
<div> {{$store.getters.getNum}},{{$store.state.b.username}} </div>
8-6 使用命名空间 ,解决多个模块中有相同状态或函数的冲突问题
const moduleA = {
//命名空间, 此时使用模块的状态必须加模块名称
namespaced: true,
...
}
<div>{{ $store.getters['a/getNum'] }}</div>
this.$store.commit('a/addSync', num)
9 mapState mapGetters mapMutatios mapActions 辅助函数
function mapState(arr){
let _this = this
let object = {}
for(let item of arr){
object[item] = ()=>{
return _this.$store.state[item]
}
}
return object
}
let object = mapState(['a','b','c'])
object ={
a(){
return _this.$store.state['a']
}
b(){
return _this.$store.state['b']
}
c(){
return _this.$store.state['c']
}
}
//
{{a}} {{b}} {{c}}
computed:{
// ...object
...mapState(['a','b','c'])
}
<template>
<div class="home">
<div>全局命名空间的数据:</div>
<div>{{ 'a=' + a }}</div>
<div>{{ 'b=' + JSON.stringify(b) }}</div>
<div>{{ 'c=' + c }}</div>
<div>{{ getA }}</div>
<div><button @click="mutateA(100)">mutateA</button></div>
<div><button @click="asyncMutateA(1000)">asyncMutateA</button></div>
<hr />
<div>some命名空间的数据:</div>
<div>{{ 'a=' + m_a }}</div>
<div>{{ get_A }}</div>
<div><button @click="mutate_A(200)">mutate_A</button></div>
<div><button @click="asyncMutate_A(2000)">asyncMutate_A</button></div>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
name: 'HomeView',
data() {
return {}
},
computed: {
// 全局命名空间的状态
...mapState(['a', 'b', 'c']),
// 模块some中的状态
...mapState({ m_a: (state) => state.some.a }),
// 全局命名空间的getters
...mapGetters(['getA']),
// some命名空间的getters
...mapGetters({ get_A: 'some/getA' }),
},
methods: {
// 同步修改
...mapMutations(['mutateA']),
...mapMutations({ mutate_A: 'some/mutateA' }),
// 异步修改
...mapActions(['asyncMutateA']),
...mapActions({ asyncMutate_A: 'some/asyncMutateA' }),
},
}
</script>
vuex 基本使用
于 2022-09-16 10:37:45 首次发布