Vue Vuex中的严格模式/实例解析/dispatch/commit /state/getters

严格模式

    import getters from './getters'
    import mutations from './mutations'
    import actions from './actions'
    export default new Vuex.Store({
      strict: true, //严格模式开启
      state: {  // 全局state
      },
      modules:{ // 外部模块
      },
      getters, // 全局getters
      mutations, // 全局mutation
      actions, // 全局actions
    })
    // 如果在vue页面中直接修改state 会报错
    this.$store.state.namespace.stateName= '直接修改state'
    // Error: [vuex] Do not mutate vuex store state outside mutation handlers.

this.$store 实例解析

// 在主入口文件main.js 或者 index.js 中,一旦引入并use了store实例后,
// 在new Vue({})之后,
// 便可以在任意vue文件中使用 this.$store来使用store中state/action/mutation
import store from './store'
Vue.use(store)
new Vue({
  router, 
  store,
  template: '<app/>',
  components: { App }
})

// A.vue 
console.info(this.$store)
/**
commit: ƒ (e,t,a)
dispatch: ƒ (e,t)
getters: {…} // 包含了在 new Vuex.Store({getters})的所有属性
strict: true
_actionSubscribers: []
_actions:  // 包含全部的action, 全局的和module中的
_committing: false
_modules: c {root: s}
_modulesNamespaceMap: // 每个单独module的命名空间 /user, /dictionary, /list
_mutations: // 包含全部的mutations,  全局的和module中的
_subscribers: []
state: (...) // 包含全部的state, 全局的和module中的
**/

state

    // 直接调用 state 
    console.info('this.$store.state.user.flag:', this.$store.state.user.flag) 

getters

    // 直接调用 getters(前提是在getter中声明了某个state), example: flag: state => state.user.flag,
    console.info('this.$store.getters.flag:', this.$store.getters.flag)
    // 会获取同样的值

dispatch

    // dispatch执行的 action
    // this.$store.dispatch('user/actionName')

    // demo
    console.info(' ##### Before dispatch #####')
    this.$store.dispatch('StartLoading')
    console.info('this.$store.state.loading:', this.$store.state.loading) // true
    this.$store.dispatch('EndLoading')
    console.info(' ##### After dispatch #####')
    console.info('this.$store.state.loading:', this.$store.state.loading) // false

commit

    // commit执行的是mutation
    // this.$store.commit('namespace/mutationName')
    
    // demo
    console.info(' ##### Before commit #####')
    console.info('this.$store.state.user.flag:', this.$store.state.user.flag) // I am flag
    console.info('this.$store.getters.flag:', this.$store.getters.flag) // I am flag
    this.$store.commit('user/SET_FLAG', 'commit mutation to change state') 
    console.info(' ##### After commit #####')
    console.info('this.$store.state.user.flag:', this.$store.state.user.flag) // commit mutation to change state
    console.info('this.$store.getters.flag:', this.$store.getters.flag) // commit mutation to change state

猜你喜欢

转载自www.cnblogs.com/leslie1943/p/13371398.html