Vuex Vue应用程序开发的状态管理模式
2020-5-25
Vue 扩展包
Vue
vuex

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

安装

CDN

<script src="https://unpkg.com/vuex"></script>

NPM

npm install vuex --save

Yarn

yarn add vuex

使用

src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import test from './modules/test'
...
Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  modules: {
    test,
    ...
  },
  strict: debug
})

src/store/modules/test.js

// initial state
const state = () => ({
  all: []
})

// getters
const getters = {}

// actions
const actions = {
  getData ({ commit }) {
    let data = {}
    commit('setData', data)
  }
}

// mutations
const mutations = {
  setData (state, data) {
    state.all = data
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

src/main.js

import Vue from 'vue'
import store from './store'
...
new Vue({
  el: '#app',
  store,
  ...
  render: h => h(App)
})

更多内容查看文档https://vuex.vuejs.org/zh (opens new window)