Vue全家桶-vuex

前言


在实际开发中,可能N个组件共享一个数据. 我们在其中一个组件里面去修改这个共享数据,那么我还需要告诉其它与该共享数据相关联的组件. 这会显得很麻烦,可能还会导致后面代码的可维护性极差.所以vue为我们提供了vuex.

vuex

vuex 是Vue.js应用程序的状态管理模式.它充当应用程序中所有组件的集中存储,其数据只能以预测的方式进行变更.

Vue全家桶-vuex
如果组件要修改vuex共享数据,首先需要通过commit去提交. 然后引发mttations修改state里面的数据.因为state数据是响应式的,所以在它发生变化的时候会主动通知组件重新Render渲染.

注意: 在组件内不能修改共享数据,只能通过提交让vuex去修改.遵守单向数据流原则.

配置

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {}
})

state: 存放数据.
mutations: 修改数据.
actions: 异步处理.

  • 代码实例

store.js代码

export default new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    ChangeCount(state) {
      state.count += 5;
    }
  },
  actions: {}
})

组件代码

<template>
  <div id="app">

    <!-- 通过 $store.state 访问数据-->
    <p>Count: {{$store.state.count}}</p>


    <button @click=" Change">+5</button>
  </div>
</template>

<script>
export default {
  name: "app",
  methods: {
    Change() {
      // 提交commit 在mutations里面进行修改
      this.$store.commit("ChangeCount");
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>