• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • vuex 与 组合式 API

    可以通过调用useStore函数,来在setup钩子函数中访问store。这与在组件中使用选项式 API 访问this.$store是等效的。

    import {useStore } from 'vuex'
    
    export default {
      setup () {
        const store = useStore()
      }
    }
    


    访问 State 和 Getter

    为了访问stategetter,需要创建computed引用以保留响应性,这与在选项式 API 中创建计算属性等效。

    import { computed } from 'vue'
    import { useStore } from 'vuex'
    
    export default {
      setup () {
        const store = useStore()
    
        return {
          // 在 computed 函数中访问 state
          count: computed(() => store.state.count),
    
          // 在 computed 函数中访问 getter
          double: computed(() => store.getters.double)
        }
      }
    }
    


    访问 Mutation 和 Action

    要使用mutationaction时,只需要在setup钩子函数中调用commitdispatch函数。

    import { useStore } from 'vuex'
    
    export default {
      setup () {
        const store = useStore()
    
        return {
          // 使用 mutation
          increment: () => store.commit('increment'),
    
          // 使用 action
          asyncIncrement: () => store.dispatch('asyncIncrement')
        }
      }
    }