【Vue】Vue学习(四)-状态管理中心Vuex的简单使用

一.vuex的简介

  Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。Vuex背后的基本思想,就是前面所说的单向数据流。图4就是Vuex实现单向数据流的示意图。

  

     Store

     每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state) 。

    

  State

    Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (SSOT)”而存在。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。

  Mutations

    Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数(handler)。

  Action

  Action 类似于 mutation,不同在于:

      1.Action 提交的是 mutation,而不是直接变更状态。 

      2.Action 可以包含任意异步操作。

二.vuex的配置

  定义store.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  //stat里面就是用来定义对象 ---给mutations和actions这两部分使用
  state: {
    //这里定义了count对象
    count: 0,
  },
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  },
  //mutations里面去注册事件---就是定义很多方法,给其他组件用
  mutations: {
    add(state) {
      state.count ++
    },
    decrease(state) {
      state.count --
    }
  },
  //actions里面去使用事件
  actions: {
    delayAdd(context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000);
    }
  }
})

  在计算属性中监听对象的变化,并且提供映射

//使用计算属性的方式
computed: {
    count() {
      return this.$store.state.count
    }
  }

//使用**********辅助函数***********的方式
//引入辅助函数
import { mapState, mapGetters } from 'vuex' export default { computed: { //...mapState表示展开,这样的好处是在computed里面,既能使用辅助函数,也能使用在computed里面使用其他计算属性
    ...mapState({
    //count: state
=> state.text.count模块化的方式,vuex模块化之后,只能这样监听计算属性

   count:this.$store.text.count
    }),
    ...mapGetters([
      'doubleCount'
    ])
  },

使用$stor.commit或者dispatch去分别触发 mutations 或者 actions里面的方法

  methods: {
    add() {
      //this.$store.commit是用来触发mutations
      this.$store.commit('add')
      //this.$store.dispatch是用来触发actions的操作
      this.$store.dispatch('delayAdd')
    }
  },

三.Vuex模块化的配置

  建立一个store文件夹

  

  将对应的模块导出,引入到index.js里面即可

       

 四.Vuex中的计算属性getters

原文地址:https://www.cnblogs.com/july-sunny/p/12424174.html