十分钟掌握使用 Vuex 4.x (vue 3.x)

108 阅读1分钟

Vuex 4.x 文档

Vuex 4.x api文档

安装 Vuex

npm#

npm install vuex@next --save

Yarn#

yarn add vuex@next --save

一: createStore: Store 构造器选项,创建一个 store 实例

import { createStore } from 'vuex'

import app from './app'
import app2 from './app2'
import getters from './getters'

const store = createStore({
  state: {
    count: 0name: 'xiaogao'
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 `context.commit` 提交一个 mutation,或者通过 `context.state` 和 `context.getters` 来获取 state 和 getters。
    incrementAsync (context) {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)

    }
  },
  getters: getters,
  modules: {
    app,
    app2
  }
})
export default store

二: 将 store 实例作为插件安装, 这样所有的组件都可以使用store中的数据了

import { createApp } from 'vue'
import store from './store'

const app = createApp({ /* 根组件 */ })

// 将 store 实例作为插件安装
app.use(store)

三:将 store 实例作为插件安装, 这样所有的组件都可以使用store中的数据和方法了 (必须有第二步方可以在任意组件中使用store中的数据就方法)

<template>
  <div class="common-layout layout-container-demo" >
    <div >
      {{name}}
    </div>
    <div >
      {{count}}
    </div>
    <button @click="increment" >
      count++
    </button>
  </div>
</template>


export default {
  ...
  computed: {
    name() {
      return this.$store.state.name;
    },
    count() {
      return this.$store.state.count;
    },
  },
  methods: {
    increment() {
      this.$store.commit('increment')
      console.log(this.$store.state.count)
    },
    increment2() {
      this.$store.dispatch('incrementAsync')
      console.log(this.$store.state.count)
    },
  }
  ...
}

四: 将 store 实例作为插件安装, 这样所有的组件都可以使用store中的数据了

import store from './store'


store.commit('increment')
console.log(store.state.count) 


// 或
store.dispatch('incrementAsync')
console.log(store.state.count) 

上一篇讲述了 十分钟学会使用 Vuex 3.x (vue 2.x)