vuex
状态管理
vuex 状态管理demo
vuex
5个属性 state
, getters
, mutations
, actions
, modules
01) 基本目录结构(自己创建)
1 2 3 4 5 6
| src --vuex ------actions.js ------getters.js ------index.js ------mutations.js
|
02) src/vuex/index.js
内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import Vue from 'vue' import Vuex from 'vuex'
import mutations from './mutations' import actions from './actions' import getters from './getters'
Vue.use(Vuex);
const state = { count: 10 };
const store = new Vuex.Store({ state, mutations, actions, getters });
export default store
|
03)src/vuex/mutations.js
内容
1 2 3 4 5 6 7 8
| const mutations = { increment_vuex(state) { state.count++ } };
export default mutations
|
04)src/vuex/actions.js
内容
1 2 3 4
| const actions = {};
export default actions
|
05)src/vuex/getters.js
内容
1 2 3 4
| const getters = {};
export default getters
|
06)src/main.js
注册vuex
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import Vue from 'vue' import App from './App.vue' import router from './router/index' import store from './vuex/index'
Vue.config.productionTip = false
Vue.prototype.$dafei = "我是自定义全局变量";
new Vue({ render: h => h(App), router, store }).$mount('#app');
|
07)src/App.vue
中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div id="app"> {{ $route.meta.title}} ---我是元数据title <input type="button" value="点击vuex" @click="increment()"> <router-view></router-view> </div> </template>
<script> export default { name: 'app', methods:{ increment() { this.$store.commit('increment_vuex'); console.log(this.$store.state.count); } } } </script>
|

Module 模块化
这里暂时不做介绍
辅助函数
辅助函数 mapState
mapGetters
mapMutations
mapActions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const book={ state:{ bookState:"001", bookStateName:"大飞", foo: "123", bar: "456" }, getters: { bookFoo: state => state.bookStateName + '123', }, mutations: { SET_FOO: (state, newVal) => { state.foo = newVal; }, SET_BAR: (state, newVal) => { state.bar = newVal; } }, actions: { update({commit}, info) { commit('SET_BAR', info); } },
}
export { book }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| export default { data() { return {} }, computed: { ...mapState(['book']), ...mapGetters(['bookFoo']), }, created() { this.SET_FOO('abc') this.update('xyz') }, methods: { ...mapMutations(['SET_FOO']), ...mapActions(['update']), }, };
|
vuex状态管理