Vuex 状态管理器

为什么要用Vuex???

   由于Vue是单向数据流,子组件内部不能直接修改从父级传递过来的数据,子组件与子组件之间无法相互传递数据。如果我们想让两个子组件之间进行通信的话,可以借助子组件 A 向父组件传值,父组件接收子组件 A 的数据后再传给 B 组件这样的方式进行通信。

 

但是这样会有一个问题,就是如果子组件 A 的父组件上面还有一层爷爷组件,或者还有更多祖父类型的层级,会很麻烦。

 因此,我们会想到能不能我们将一个共有的数据存在一个特定的地方,用的时候自己去拿,这样就不需要一层层传值,于是乎 Vuex 就应运而生了。

 

【干货来袭!!!】

1. 从 store 实例中读取状态最简单的方法就是在组件中的计算属性computed中返回某个状态

2. Getter 接受 state 作为其第一个参数,也可以接受其他 getter 作为第二个参数

3. 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,它会接受 state 作为第一个参数,也可以向 store.commit 传入额外的参数,即 mutation 的 载荷

4. Mutation是同步,action是异步。Action 提交的是 mutation,而不是直接变更状态。

5. Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

 

 

 

[ 代码 ]:  

src/store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    text: 'I come from Vuex',
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ],
    count: 0
  },
  getters: {
    doneToDos (state) {
      return state.todos.length
    }
  },
  mutations: {
    changeBtnCount (state) {
      state.count++
    },
    resetBtnCount (state) {
      state.count = 0
    }
  },
  actions: {

  }
})

src/views/Home/index.vue

<template>
  <div>
    <p>
      state: {{ textFromVuex }} ---------  getters: {{ numFromVuex }} 
    </p>
    <p>
      直接拿状态管理器:{{ this.$store.state.text }}
    </p>
    <div>
      <button @click="clickTimeBtn">点击了 {{ clickTimes }} 次</button>
      <button @click="resetTimeBtn" style="margin-left:20px">重置</button>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    // 从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:
    textFromVuex () {
      return this.$store.state.text
    },
    numFromVuex () {
      return this.$store.getters.doneToDos
    },
    clickTimes () {
      return this.$store.state.count
    }
  },
  mounted () {
  },
  methods: {
    clickTimeBtn () {
      this.$store.commit('changeBtnCount')
    },
    resetTimeBtn () {
      this.$store.commit('resetBtnCount')
    }
  }
}
</script>

<style>

</style>
原文地址:https://www.cnblogs.com/edwardwzw/p/12101676.html