主题
Vuex
介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理库。
安装
bash
npm install vuex@3
项目搭建
bash
/src
/store
/modules
counter.js
user.js
...
index.js
js
const counter = {
namespaced: true,
// 初始化 state
state: () => ({
count: 0,
}),
// 同步操作,直接修改
mutations: {
INCREMENT(state, val) {
state.count += val
},
DECREMENT(state, val) {
state.count -= val
},
},
actions: {
increment({ commit }, val) {
commit('INCREMENT', val)
},
decrement({ commit }, val) {
commit('DECREMENT', val)
},
// 异步操作
asyncIncrement({ commit }, val) {
setTimeout(() => {
commit('INCREMENT', val * 100)
}, 3000)
},
},
}
export default counter
js
import Vue from 'vue'
import Vuex from 'vuex'
import counter from './modules/counter'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
counter,
},
})
export default store
js
import Vue from 'vue'
import store from './store'
import App from './App.vue'
new Vue({
store,
render: h => h(App),
}).$mount('#app')
使用
vue
<template>
<div>
<button @click="() => $store.dispatch('counter/increment', 2)">++</button>
<button @click="() => $store.dispatch('counter/asyncIncrement', 2)">异步 ++</button>
<span>{{ $store.state.counter.count }}</span>
<button @click="() => $store.dispatch('counter/decrement', 1)">--</button>
</div>
</template>