
当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:

export default {
    count: 0,
    firstName: 'Keyan',
    lastName: 'Liu'
}export default {
    increment(context, n) {
        // setTimeout(() => {
        //     context.commit('increment', n)
        // }, 1000)    
        context.commit('increment', n)
    }
}export default {
    increment(state, payload) {
        state.count += payload.amount
    }
}export default {
    fullName(state) {
        return `${state.firstName} ${state.lastName}`
    }
}import Vue from 'vue'
import Vuex from 'vuex'
import state from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './actions/actions'
Vue.use(Vuex)
export default new Vuex.Store({
  state,
  mutations,
  getters,
  actions
})
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <span>{{ count }}</span>
    <br>
    <button @click="fun({amount: 11})">增加</button>
    <br>
    <span>{{ fullName }}</span>
    <!-- <span>{{ countAlias }}</span> -->
  </div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
  name: 'About',
  beforeRouteEnter(to, from, next) {
    console.log('----------before enter--------', this)
    next(vm => {
      console.log('after enter vm.id is:', vm.id)
    })
  },
  beforeRouteUpdate(to, from, next) {
    console.log('-----------upadte enter--------')
    next()
  },
  beforeRouteLeave(to, from, next) {
    console.log('------------leave enter----------')
    if(global.confirm('are you sure?')) {
      next()
    }
  },
  props: ['id'],
  mounted() {
    console.log(this.id)
    console.log(this.$route)
  },
  computed: {
    ...mapState([
    'count',
    ]),
    ...mapGetters([
      'fullName'
    ])
  },
  methods: {
    ...mapMutations({
      fun: 'increment'
    }),
    ...mapActions({
      fun: 'increment'
    })
  }
}
</script>

原文:https://www.cnblogs.com/nayek/p/12060502.html