再读Vuex

vuex是vue的状态管理工具


再读Vuex_第1张图片
单向数据流

在components中通过dispatch来触发actions,actions通过commit来触发mutations,mutations最终触发state的变更,state的变更引起组件中computed计算属性的响应,从而反应到组件中。

注意点归纳

  1. 为了避免在需要使用state的组件中频繁地导入store管理模块,vuex提供了注入的机制,从根组件将stroe注入所有组件,且子组件能通过 this.$store 访问到。
const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter }
})
  1. mapState辅助函数,当一个子组件需要依赖多个state,通过在计算属性中使用mapState辅助函数,将所有需要的state 混入 计算属性中,当任一state改变,将触发计算属性重新计算。
computed: mapState(['toast'])
//当计算属性还需要计算其他的数据时,使用ES2015的...解构方法,将所有state混入计算属性。...对象展开运算符将其解构成对象属性的形式,而不是对象的形式。
computed:{
          otherdata(){},
          ...mapState(['xx','xxx'])
}
  1. Getter相当于State的filter,可以将state数据进行一些操作之后再返回给组件,当需要这个过滤器时,mapState辅助函数还可以替换为mapGetter辅助函数,再混入computed,监听过滤后的state。
import { mapGetters } from 'vuex'
export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
  1. Vuex中更改store的唯一方法是提交mutation(突变),mutations中定义突变函数名,通过commit('突变函数名')来触发mutation,多数情况下,突变函数应接受两个参数,一个是突变的state,一个是payload(载荷,一个有关突变数据的对象)。
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})
/***********************************************/
/***在组件中,可以将需要的突变函数混入method方法***/
import { mapMutations } from 'vuex'
export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}
  1. 在mutation之中只能进行同步的操作,所有的异步操作需要放到action中,再然后,通过dispatch来触发action,action是通过commit mutation来实现变动的。Action也可以在methods中通过...mapAction来分发action。例如:
 getArticles: ({commit}) => {
    const start = beginLoading(commit)
    return Vue.http.get('/api/getArticles')
      .then(response => response.json())
      .then(articles => {
        stopLoading(commit, start)
         //触发mutation
         commit('SET_ARTICLES', articles)
      })
  }
  1. 上方({commit})的操作的解释,commit为从 函数实参对象中提取的数据,传入函数的还是一个包含此commit函数对象的对象。
    再读Vuex_第2张图片
    image.png

长路漫漫,
勿忘初心 。

你可能感兴趣的:(再读Vuex)