验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Vuex3和Vuex4的区别是什么

阅读:887 来源:乙速云 作者:代码code

Vuex3和Vuex4的区别是什么

Vuex 是 Vue.js 的官方状态管理库,用于在 Vue.js 应用中管理应用状态。Vuex 3 是用于 Vue 2 的版本,而 Vuex 4 是用于 Vue 3 的版本。下面是 Vuex 3 和 Vuex 4 在一些重要方面的异同点:

创建 Store 的方式

  • Vuex 3:使用 new Vuex.Store() 创建 store 实例

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 配置项
})

export default store
  • Vuex 4:使用 createStore 函数创建 store 实例

import { createStore } from 'vuex'

const store = createStore({
  // 配置项
})

export default store

Vuex 4 中使用 createStore 函数来创建 store 实例,而不是直接在 Vue 实例上挂载。

在组件中使用 Store

  • Vuex 3:使用 this.$store 访问 store 实例,通过 this.$store.state 访问状态,通过 this.$store.commit() 进行提交 mutation,通过 this.$store.dispatch() 进行分发 action。

export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment')
    },
    incrementAsync() {
      this.$store.dispatch('incrementAsync')
    }
  }
}
  • Vuex 4:使用 useStore 函数来获取 store 实例,通过 store.state 访问状态,通过 store.commit() 进行提交 mutation,通过 store.dispatch() 进行分发 action。

import { useStore } from 'vuex'

export default {
  setup() {
    const store = useStore()
    const count = computed(() => store.state.count)

    const increment = () => {
      store.commit('increment')
    }

    const incrementAsync = () => {
      store.dispatch('incrementAsync')
    }

    return {
      count,
      increment,
      incrementAsync
    }
  }
}

虽然 Vuex4 推荐使用更符合 Composition API 风格的 useStore() 来获取 store 实例。但是并没有移除 this.$store,但是在