Vuex状态管理模式(入门)

174 阅读1分钟
安装:npm install vuex --save
//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state:{},//状态
    mutations:{},//方法
    actions:{},//异步方法
    getters:{},//计算
    modules:{}//模块
})
export default store
//main.js
//导入
import store from './store.index'
new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

1.state

用于存放数据,与data类似
state:{
	name:'Tom',
    age:18
}
//在组件中使用
this.$store.state.name
this.$store.state.age
▲通过this.$store.state 也可以修改数据,但是不推荐这种操作方式,
因为通过这种方式进行就该不会产生记录,在调试或发生错误时难以排查

正确的修改方式: Acrions里处理异步代码,无异步可省略, Mutations里处理同步代码

2.Mutations

用于处理同步代码,改变数据,等
mutations:{
	//参数state为state对象
	changeName(state){
    	state.name = 'Ban'
    }
}
使用:this.$store.commit('方法名')
可以带参数:
	方式一:this.$store.commit('changeName','Van')
    方式二:this.$store,commit({
    	type:'changeName',
        name:'Van'
    })
mutations:{
	changeName(state,name){
    	state.name = name
    }
}

mutations的类型常量

使用类型常量是官方推荐的,这样对于多人项目会减少命名出错的问题
//mutations-type.js
export const CHANGENAME = 'changeName'
//store.js
import {CHANGENAME} from './mutaions-type'
...
mutations:{
	[CHANGENAME](state,name){
    	state.name = name
    }
}
//使用的组件
import {CHANGENAME} from '@/store/mutaions-type'
...
this.$store.commit(CHANGENAME,'Van')

3.getters

对数据进行处理,类似computed
//store.js
const store = new Vuex.Store({
	state:{
    	arr:[1,2,3,4,5]
    },
    getters:{
    	arrExceed3(state){
        	return state.arr.filter(item=>{
                return item > 3
            })
        }
    }
})
//组件使用
this.$store.getters.arrExceed3
通过return一个函数的形式实现getters带参
//store.js
const store = new Vuex.Store({
	state:{
    	arr:[1,2,3,4,5]
    },
    getters:{
    	arrExceed3(state){
        	return function(num){
              return state.arr.filter(item=>{
                  return item > num
              })
            }
        }
    }
})
//组件使用
this.$store.getters.arrExceed3(3)

使用方式二:mapGetters 对象展开

使用此种方式后使其变得与普通计算属性一样使用。
import {mapGetters} from 'vuex'
...
computed:{
    ...mapGetters([
      'arrExceed3'	//getters的方法名
    ])
  },
——————————————————————————————————————
//可以自己命名
computed:{
    ...mapGetters([
      newArr:'arrExceed3'	
    ])
  },

4.actions

异步操作处理
//store.js
const store = new Vuex.Store({
    state:{
        nums:18,
    },
    mutations:{
        ageAdd(state,num){
            state.nums+=num
        }
    },
    actions:{
    //context是$store实例
        after2seconds(context,num){
            setTimeout(()=>{
                context.commit('ageAdd',num)
            },2000)
        }
    }
})
//组件使用
//也可以载参
this.$store.dispath('after2seconds',3)
处理异步操作逻辑,如需数据请求成功再进行操作

方式一,使用回调函数

//store.js
actions:{
        after2seconds(context,num,callback){
            setTimeout(()=>{
                context.commit('ageAdd',num)
                callback()//调用函数
            },2000)
        }
    }
//组件使用
this.$store..dispath('after2seconds',3,function(){
	console.log('成功O(∩_∩)O')
})

方式二:使用Promise

//store.js
actions:{
        aafter2seconds(context, num) {
            return new Promise(resolev => {
                setTimeout(() => {
                    context.commit('ageAdd', num)
                    resolev()
                }, 2000)
            })
        }
    }
//组件使用
this.$store..dispath('after2seconds',3)
	.then(()=>{
    	console.log('成功O(∩_∩)O')
    })
    .catch(()=>{
    	console.log('失败>︿<')
    })

5.modules

将store分割成一个个模块,每个模块都拥有自己的
state,mutations,actions,getter,modules
const store = new Vuex.Store({
	modules:{
    	moduleA:{
        	state:{},
            getters:{},
            mutations:{},
            actions:{},
            modules:{}
        },
        moduleB:{
        	state:{},
            getters:{},
            mutations:{},
            actions:{},
            modules:{}
        },
    }
})
modules访问局部状态:context.state
	   访问根部状态:context.rootState