简单浅显的理解Vuex(初步)

Vue-CLI 3.0集成Vuex,默认文件为store.js

内容:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vue.Store({
    *****
})

官方文档中的五个状态:

1.State 

单一状态树,简单来说就是定义初始值的位置。

state:{
    *****
}

全局获取方法:this.$store.state.***

2.Getter

类似计算属性(实时监听),带有更新状态,获取更新后的最新状态值。

全局获取方法:this.$store.getters.***

getters:{
    ***(state){    //函数名自定
        return state.***    //state.*** => 想要监听的值
    }
}

3.Mutation

更改store中状态的唯一方法,提交mutation

定义:

mutations:{
    ***(state){    //函数名自定
        //值(状态)的变更
        state.*** = ***  //要改变的状态
    }
}

全局调用:

this.$store.commite(' *** ') // 触发一个类型为***的mutation

还可以传入额外参数(提交载荷):

mutations:{
    ***(state,n){       //函数名自定
        state.*** += n //任意操作
    }
}

调用:

this.$store.commit('***',n的值)

大多数情况,传入的应该是一个对象,好处:易读

例如文档的例子:

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
//全局调用
this.$store.commit('increment', {
  amount: 10
})

需要注意的是:muntation必须是同步函数

4.Action

写法:将mutation中想要进行异步操作的方法包裹在内

特点:提交mutation,支持异步操作(任意)

//定义
mutations:{
    increment(state){
       state.count++
    }
},
actions:{
    increment(context){
        context.commit('increment')
    }
}
//调用:
this.$store.dispatch('increment')

异步:

actions: {
  incrementAsync ({ commit }) {    //解构写法    
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

另:同样支持传值(载荷)

5.Model

允许将store分为模块:

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

如果不重定命名空间,公共调用同上,待深入

猜你喜欢

转载自blog.csdn.net/weixin_41564885/article/details/85621014