vuex
状态管理模式
state:共享数据源;
mutations:修改数据(state中的数据);
actions:异步请求;
getters:对共享数据进行包装(类似计算属性);
modules: 模块化
代码
vuex代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0,
arr: [1, 3, 6, 7, 4, 10]
},
mutations: {
addCount(state, payload) {
state.count += payload
}
},
actions: {
asyncAddCount(context, payload) {
setTimeout(() => {
context.commit('addCount', payload)
}, 2000)
}
},
getters: {
getterCount: state => state.arr.filter(item => item > 5),
// 快捷访问
token: state => state.user.token,
name: state => state.settings.name
},
modules: {
// ! 命名空间
user: {
namespaced: true,
state: {
token: 11111
},
mutations: {
changeToken(state, payload) {
state.token = payload
}
}
},
settings: {
state: {
name: '标题'
}
}
}
})
vue组件中使用方式
<template>
<div id="app">
<!-- #1 state -->
<!-- 方式一 $store.state.count -->
<h4>{{ $store.state.count }}</h4>
<!-- 方式二 mapState(['count']) -->
<h4>{{ count }}</h4>
<!-- #2 getters -->
<!-- 方式一 $store.getters.getterCount -->
<h4>getter:{{ $store.getters.getterCount }}</h4>
<!-- 方式二 mapGetters(['getterCount']) -->
<h4>getter:{{ getterCount }}</h4>
<!-- #3 mutations -->
<!-- 方式一 mapMutations(['addCount']) -->
<div><button @click="addCount(1)">+1</button></div>
<!-- 方式二 $store.commit('addCount', 100)-->
<div><button @click="$store.commit('addCount', 100)">+100</button></div>
<!-- #4 actions -->
<!-- 方式一 $store.dispatch('asyncAddCount', 2) -->
<div>
<button @click="$store.dispatch('asyncAddCount', 2)">async+2</button>
</div>
<!-- 方式二 mapActions(['asyncAddCount']) -->
<div>
<button @click="asyncAddCount(10)">async+10</button>
</div>
<!-- #5 modules 模块化 -->
<!-- state -->
<h4>{{ $store.state.user.token }}</h4>
<h4>{{ $store.state.settings.name }}</h4>
<h4>{{ token }}</h4>
<h4>{{ name }}</h4>
<!-- 采用 namespaced 后的模块调用mutations或actions的方式 -->
<!-- 方式一 createNamespacedHelpers -->
<div>
<button @click="changeToken(10)">修改user的token 1</button>
</div>
<!-- 方式二 $store.commit('user/changeToken', 233) -->
<div>
<button @click="$store.commit('user/changeToken', 233)">
修改user的token 2
</button>
</div>
<!-- 方式三 mapMutations(['user/changeToken']) -->
<div>
<button @click="changeT(2233)">
修改user的token 3
</button>
</div>
</div>
</template>
<script>
import {
mapState,
mapMutations,
mapActions,
mapGetters,
createNamespacedHelpers
} from 'vuex'
const { mapMutations: userMapMutations } = createNamespacedHelpers('user')
export default {
name: 'App',
computed: {
...mapState(['count']),
...mapGetters(['getterCount', 'name', 'token'])
},
methods: {
...mapMutations(['addCount', 'user/changeToken']),
...mapActions(['asyncAddCount']),
...userMapMutations(['changeToken']),
changeT(val) {
this['user/changeToken'](val)
}
}
}
</script>