Vuex的核心概念

State

State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储

const store = new Vuex.Store({
  state:  { count: 0 }
})
组件访问State中数据的第一种方式:
this.$store.state.count
组件访问State中数据的第二种方式:

通过导入mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性

import { mapState } from 'vuex'

computed:{
...mapState(['count'])
}

Mutation

mutation用于变更Store的数据

  • 只能通过mutation变更Store数据,不可以直接操作Store中的数据
  • 可以集中监控所有数据的变化
  • 只能写同步代码
const store = new Vuex.Store({
  state:  { count: 0 },
//定义Mutation
  mutations: {
    ADD_COUNT: (state) => {
      state.count++
    },
    //传递参数
   ADD_NCOUNT: (state, step) => {
      state.count =+ step
    }
  }
})
触发mutation的第一种方式
this.$store.commit('ADD_COUNT')
this.$store.commit('ADD_NCOUNT',3) // 传递参数 
触发mutation的第二种方式:

通过导入mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法

import { mapMutations } from 'vuex'

methods:{
...mapMutations([ 'ADD_COUNT', 'ADD_NCOUNT' ])
//使用 this.ADD_COUNT() this.ADD_NCOUNT(3)
}

Action

如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是Action中还是要通过触发Mutation的方式间接变更数据

const store = new Vuex.Store({
 state:  { count: 0 },
//定义Mutation
 mutations: {
   ADD_COUNT: (state) => {
     state.count++
   },
   //传递参数
   ADD_NCOUNT: (state, step) => {
     state.count =+ step
   }
 },
 actions:{
   addAsync({commit}) {
    setTimeout( () => {
      commit('ADD_COUNT')
     },1000) 
   }
 }
})
触发Action的第一种方式
this.$store.dispatch('addAsync')
触发Action的第二种方式

通过导入mapActions函数,将需要的actions函数,映射为当前组件的methods方法

import { mapActions} from 'vuex'

methods:{
...mapActions([ 'addAsync' ])
//使用 this.addAsync()
}

Getter

  • Getter可以对Store中已有的数据加工处理形成新的数据,类似Vue的计算属性
  • Store中数据发生变化,Getter的数据也会跟着变化
const store = new Vuex.Store({
  state:  { count: 0 },
//定义Mutation
  mutations: {
    ADD_COUNT: (state) => {
      state.count++
    },
    //传递参数
    ADD_NCOUNT: (state, step) => {
      state.count =+ step
    }
  },
  actions:{
    addAsync({commit}) {
     setTimeout( () => {
       commit('ADD_COUNT')
      },1000) 
    }
  },
  getters:{
    showCount: state => state.count
  }
})
使用getters的第一种方式
this.$store.getters.showCount
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vuex 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。 使用 Vuex 统一管理状...
    zlog阅读 88评论 0 1
  • Vuex的核心概念 State state提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中...
    淺時咣阅读 430评论 0 2
  • State 单一状态树 Vuex使用单一状态树——用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据...
    oWSQo阅读 1,112评论 0 0
  • 本文为转载,原文:Vue学习笔记进阶篇——vuex核心概念 前言 本文将继续上一篇 vuex文章 ,来详细解读一下...
    ChainZhang阅读 1,673评论 0 13
  • (1)安装 (2) State: Vuex使用单一状态树,state作为唯一数据源 (SSOT)而存在 Vuex ...
    __越过山丘__阅读 240评论 0 0