# 官方文档:

vue2 对应的路由: vuex@3 (opens new window)

vue3 对应的路由: vuex@4 (opens new window)

# 1、vuex 使用

  由于 vue3 采用的是 composition api,所以使用 vuex 有些许不同:

  • vuex@3 中
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

export default store
  • vuex@4 中
import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
  // state() {
  //   return {
  //     count: 0
  //   }
  // },
  state: () => ({
    count: 0
  })
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

export default store

# 2、辅助函数

  • vuex@3 中
<script>
// import { mapMutations, mapState } from 'vuex'

export default {
  computed: {
    // ...mapState(['count']),

    stateCount() {
      return this.$store.state.count
    }
  },
  methods: {
    // ...mapMutations(['increment']),

    increment() {
      this.$store.commit('increment')
    }
  }
}
</script>
  • vuex@4 中
setup 中使用辅助函数(不好用)
  • 方法 1
<script setup>
import { toRefs, computed, mapState } from 'vue'
import { useStore } from 'vuex'
const store = useStore()

// const { count } = toRefs(store.state)

const { count } = mapState(['count'])
const storeCount = computed(count.bind({ $store: store }))
</script>
  • 方法 2
// hooks/useState.js
import { computed } from 'vue'
import { useStore, mapState } from 'vuex'

export default function useState(mapper) {
  const store = useStore()
  const stateFnsObj = mapState(mapper)

  const newState = {}
  Object.keys(stateFnsObj).forEach((key) => {
    newState[key] = computed(stateFnsObj[key].bind({ $store: store }))
  })

  return newState
}
<script setup>
import { toRefs } from 'vue'
import useState from '@/hooks/useState.js'
import { useStore } from 'vuex'
const store = useStore()

// const { count } = toRefs(store.state)

const { count } = useState(['count'])
</script>
<script setup>
import { toRefs } from 'vue'
import { useStore } from 'vuex'
const store = useStore()

const { count } = toRefs(store.state)
// 或者
const { count } = computed(() => store.getters.count)
// 或者
store.dispatch('getXxxAction')

function increment() {
  store.commit('increment')
}
</script>
更新于 : 7/8/2024, 10:21:14 AM