VUEX

190 阅读1分钟

vuex的作用

  非父子关系的相互通讯

vuex是什么

   vue官方的 集中维护公共状态;
   它是一个仓库管理员,专职管理项目中的公共数据

vuex的五个要素

image.png

state
统一定义公共数据(类似于data)
mutations
作用:修改公共数据
定义格式:

mutations: { 名字(state,载荷(在执行函数时要传入的数据)){ } }

使用格式`:

1.this.$store.commit('mutations的名字',参数)

2.1)methods:{...mapMutations(['mutations的名字'])} 2.2)this.mutations名字()

注意:参数只能有一个,如果希望传递复杂数据要传递对象
getters
   从现有的state中派生出新的数据项(类似于compoted)
   定义格式:

getters:{ getters的名字:function(stats){ return 要返回的值 } }

    使用格式:

1.$store.getters.getters的名字

2.computed:{ ...mapState(['数据项1','数据项2']) }

2.computed:{ ...mapState({映射到的组件名,'数据项'}) }

actions
  发送异步请求
  定义格式:

actions: {

action的名字: function(context, 载荷) {

// 1. 发异步请求, 请求数据

// 2. commit调用mutation来修改/保存数据

context.commit('mutation名', 载荷)

} }

 注意:context对象会自动传入,它与store示例具有相同的方法和context对象

 调用格式:

this.$store.dispatch('actions的名字', 参数)

 action一般用来发异步请求,数据回来之后,在去调用mutations来保存数据    

image.png

modules
作用:拆分复杂业务(拆分模板)
    定义格式
export default ({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
  	模块名1: {
    		// 这个为true,则在使用mutations时,就必须要加上模块名
            namespaced: true, 
            state: {},
            getters: {},
            mutations: {},
            actions: {},
            modules: {}
            },
        模块名2: {
            state: {},
            getters: {},
            mutations: {},
            actions: {},
            modules: {}
                 }  
    }
})
调用格式:{{$store.state.模块名.数据项名}}

注意:
1.当namespaced的值为true,则在使用的时候必须要加上模块名(一般都是为ture0)    

$store.commit('模块名/mutations名')

2.当namespaced的值为false,则使用的时候不需要补充模块名

$store.commit('mutations名')

vuex-辅助函数map

当某个数据嵌套太深了(.的名字长),可以使用map辅助函数

image.png

mapState
直接使用:this.$store.state.xxx
全局使用
map辅助函数:

computed:{ ...mapState(['xxx']) ...mapState({'新名字':'xxx'}) }

使用modules中的state
直接使用:this.$store.state.模块名.xxx
map辅助函数:

computed:{ ...mapState('模块名',['xxx']) ...mapState('模块名',{'新名字':'xxx'}) }

mapGetters
直接使用:this.$store.getters.xxx
全局使用
map辅助函数:

computed:{ ...mapGetters(['xxx']) ...mapGetters({'新名字':'xxx'}) }

使用modules中的getters
直接使用: this.$stort.getters.模块名.xxx
map辅助函数:

computed:{ ...mapGetters('模块名',['xxx']) ...mapGetters('模块名',{'新名字':'xxx'}) }

mapMutations
直接使用: this.$store.commit('mutations名',参数)
全局使用:
map辅助函数:

computed:{ ...mapMutations(['mutations名']) ...mapMutations({'新名字':'mutations名'}) }

使用modules中的 mutations
直接使用: this.$store.commit('模块名/mutations名',参数)
map辅助函数:

computed:{ ...mapMutations('模块名',['xxx']) ...mapMutations('模块名',{'新名字':'xxx'}) }

mapActions
直接使用: this.$store.dispatch('actions名',参数)
全局使用:
map辅助函数:

computed:{ ...mapActions('mutations名') ...mapActions({'新名字':'mutations名'}) }

使用modules中 actions
直接使用: this.$store.dispatch('模块名/actions名',参数)
map辅助函数:

computed:{ ...mapActions('模块名',['xxx']) ...mapActions('模块名',{'新名字':'xxx '}) }