使用vuex管理状态数据

  • 新建store目录存储vuex-store仓库
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 7,
    testNum: 8888999
  },
  mutations: {
    add (state) {
      state.count++
    },
    sub (state) {
      state.count--
    },
    handleAdd (state, payload) {
      state.testNum = state.testNum + payload.amount
    }
  }
})

export default store
  • 其他组件使用store中存储的数据以及mutation修改
<template>
    <div>
      ComponentB: {{ testNum }}
      <button @click="handleAdd5">testNum增加6</button>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'ComB',
  computed: {
    ...mapState(['testNum'])
  },
  methods: {
    handleAdd5 () {
      // this.$store.commit({
      //   type: 'handleAdd',
      //   amount: 5
      // })
      // 使用了mapMutations之后 简化调用
      // 也可以: this['handleAdd']({amount: 1})
      this.handleAdd({amount: 6})
    },
    // mapMutations 会返回一个对象,用来简化mutation的调用
    // 将this.handleAdd 映射到 this.$store.commit('handleAdd')
    ...mapMutations(['handleAdd'])
  }
}
</script>

<style scoped>

</style>

本文链接:

http://godrry.com/archives/managing-state-data-with-vuex.html
1 + 5 =
沙发还热乎呢~