Vuex的快速上手

Vuex的快速上手

import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  getter: {
  }
})

1. state

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

state { count:0 }

组件访问的两种方式

(1) this.$store.state.count
(2) 
import { mapState } from 'vuex'
computed: {
  ...mapState(['count'])
}

注意:Store 中的数据是不可以被直接操作的 ,所以我们需要mutations

2. mutations

mutations 用于变更 Store中 的数据。

mutations: {
  add(state,step) {
    // state即为上面的共享数据源state,下同
    // step可选的第二参数
    state.count++
  }
}

组件中触发 mutations 的两种方式

(1)
methods: {
  handle() {
    this.$store.commit('add')
  }
}
(2)
import { mapMutations } from 'vuex'
methods: {
 ...mapMutations(['add'])
}

注意:在mutations中无法通过异步操作变更数据,必须通过actions

3. actions

actions 用于处理异步任务

actions:{
  addAsync(context) {
    setTimeout(()->{
      context.commit('add')
    },1000)
  }
}

触发 actions 的两种方式

(1)
methods: {
  handle() {
    this.$store.dispatch('addAsync')
  }
}
(2)
import { mapActions } from 'vuex'
methods: {
 ...mapActions(['addASync'])
}

4. getters

用于对 Store 中的数据进行加工处理形成新的数据

getter: {
	showCount: state => {
	  return 'count='+state.count
	}
}

使用的两种方式

(1) this.$store.getters.showCount
import { mapGetters } from 'vuex'
computed: {
 ...mapGetters(['showCount'])
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值