Vuex (opens new window) 是一个专为 Vue.js (opens new window) 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
<script src="https://unpkg.com/vuex"></script>
npm install vuex --save
yarn add vuex
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
})
// 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
}
import Vue from 'vue'
import store from './store'
...
new Vue({
el: '#app',
store,
...
render: h => h(App)
})