Skip to content

vuex的使用

介绍

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

安装

js
npm install vuex@next
js
import { createStore } from 'vuex'

const store = createStore({
  state: {
    count: 0,
    user: null
  },
  mutations: {
    // 修改状态的方法
  },
  actions: {
    // 处理业务逻辑的方法
  },
  getters: {
    // 计算属性的方法
  }
})

export default store

// app.use(store)
// main.js全局导入

State (状态)

js
state: {
  count: 0,
  user: {
    name: '',
    id: null
  },
  todos: []
}

// 调用
this.$store.state.count
// 组合式调用
import { computed } from 'vue'
import { useStore } from 'vuex' // 全局/局部
const store = useStore()
const count = computed(() => store.state.count)

Getter (计算属性)

js
getters: {
  doneTodos: (state) => {
    return state.todos
  },
  // 带参数的形式
  getTodoById: (state) => (id) => {
    return state.todos + id
  }
}

// 调用
this.$store.getters.doneTodos
// 组合式
import { computed } from 'vue'
import { useStore } from 'vuex' // 全局/局部
const store = useStore()
const doneTodos = computed(() => store.getters.doneTodos)

Mutations (修改state状态)

js
mutations: {
  increment (state) {
    state.count++
  },
  // 带参数的形式
  INCREMENT_BY(state, payload) {
    state.count += payload
  },
}

// 调用
this.$store.commit('increment')
// 组合式
import { useStore } from 'vuex' // 全局/局部
const store = useStore()
increment: () => store.commit('increment'),

Actions (动作,修改Mutations状态)

js
actions: {
  incrementAsync ({ commit }) {
      commit('increment')  // 执行mutations操作
  },
  // 带参数的形式
  INCREMENT_BY({ commit }, payload) {
    commit('INCREMENT_BY', payload)
  },
//   获取到state状态形式
  checkout ({ commit, state }, products) {

  }
}

// 调用
this.$store.dispatch('incrementAsync')
// 组合式
import { useStore } from 'vuex' // 全局/局部
const store = useStore()
incrementAsync: () => store.dispatch('incrementAsync'),