// store index.jsimport Vue from "vue";import Vuex from "vuex";Vue.use(Vuex);const state = { count: 0, personList:[]};const getters = { bigSum(state){ return state.count * 10 }};const actions = { // increment(context, value) { // context.commit("INCREMENT", value); // }, // decrement(context, value) { // context.commit("DECREMENT", value); // }, incrementOdd(context, value) { if(context.state.count %2){ context.commit("INCREMENT_ODD", value); } }, incrementAsync(context, value) { setTimeout(()=>{ context.commit("INCREMENT_ASYNC", value); },1000) },};const mutations = { INCREMENT(state, value) { state.count += value; }, DECREMENT(state, value) { state.count -= value; }, INCREMENT_ODD(state, value) { state.count += value; }, INCREMENT_ASYNC(state, value) { state.count += value; }, ADD(state, value){ state.personList.push({name:value}) }};export default new Vuex.Store({ state, getters, actions, mutations,});
<template> <div class="parent"> <h2>姓名:{{parentData.name}}</h2> <h2>年龄{{parentData.age}}</h2> <hr /> <H3>count当前的值:{{count}}</H3> <h2>放大10倍后的数值:{{bigSum}}</h2> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button @click="INCREMENT(n)">加</button> <button @click="DECREMENT(n)">减</button> <button @click="incrementOdd">奇数加</button> <button @click="incrementAsync">异步加</button> <hr> <h2>上方组件得长度:{{personList.length}}</h2> </div></template><script>import { mapState, mapGetters, mapMutations } from 'vuex'export default { data() { return { n: 0, parentData: { name: '我是父组件', age: '60', }, } }, computed: { //借助mapState生成得计算属性, 从state中读取数据(对象写法) ...mapState({ count: 'count', personList:'personList' }), //借助mapGetters生成得计算属性, 从getters中读取数据(数组写法) ...mapGetters(['bigSum']), }, methods: { // increment() { // this.$store.commit('INCREMENT', this.n) // }, // decrement() { // this.$store.commit('DECREMENT', this.n) // }, //借助mapMutaitions生成对应得方法, 方法中会调用commit去联系mutations //对象写法 // ...mapMutations({ // increment: 'INCREMENT', // decrement: 'DECREMENT', // }), //数组写法 ...mapMutations(['INCREMENT', 'DECREMENT']), //此处得值应该写mutations中对应得值 incrementOdd() { this.$store.dispatch('incrementOdd', this.n) }, incrementAsync() { this.$store.dispatch('incrementAsync', this.n) }, },}</script><style>.parent { padding: 20px; background: orange;}</style>
//main.jsimport Vue from 'vue'import App from './App.vue'import ElementUI from 'element-ui';import Directives from './directives/index'import 'element-ui/lib/theme-chalk/index.css';import store from './store'const bus = new Vue();Vue.prototype.bus = bus;Vue.use(Directives)Vue.config.productionTip = false;Vue.use(ElementUI);const vm = new Vue({ render: h => h(App), store}).$mount('#app')console.log(vm)