Vue Vuex 嚴格模式+實例解析+dispatch/commit + state/getter


1.嚴格模式

    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中的
**/

3. state

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

4. getters

    // 直接調用 getters(前提是在getter中聲明了某個state), example: flag: state => state.user.flag,
    console.info('this.$store.getters.flag:', this.$store.getters.flag)
    // 會獲取同樣的值

5. 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

6. 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM