vuex学习

  • 使用vuex也有一段时间了,今天总结一下vuex的使用
  • vuex有5个核心概念state ``````getter``````mutation``````action``````module

state

this.$store.state.xxx
或者使用mapState

getter

this.$store.getters.xxx
或者使用mapGetter

mutation

this.$store.commit(“xxx”)
或者使用mapMutations

action

this.$store.dispatch(“xxx”)
或者使用mapActions

module

Vuex 允许我们将store分割成模块(module)。
每个模块拥有自己的 state、mutation、action、getter

建议在使用module时,启动命名空间

案例

store.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  // 像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  },
  // 改变state中元素的数据
  mutations: {
    increment(state,n) {
      state.count += n
    },
    decrement(state) {
      state.count--
    }
  },
  // 异步提交mutations
  actions: {
    INCREMENT({commit},n) {
      commit('increment',n)
    },
    DECREMENT({commit}) {
      commit('decrement')
    },
    ASYN_INCREMENT({commit},n) {
      setTimeout(() => {
        commit('increment',n)
      },2000)
    },
  }
})

app.vue

<template>
  <div id="app">
    {{ count }}
    <br />
    {{ doubleCount }}<br />
    <button @click="INCREMENT(2)">count++</button>&nbsp;
    <button @click="DECREMENT">count--</button>&nbsp;
    <button @click="ASYN_INCREMENT(3)">异步count++</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from "vuex";

export default {
  computed: {
    ...mapState([
      'count'
    ]),
    /*
    等价于上面的写法
    ...mapState({
      count: state => state.count
    }),
    */
    ...mapGetters([
      'doubleCount'
    ])
  },
  methods: {
    ...mapActions([
      'INCREMENT',
      'DECREMENT',
      'ASYN_INCREMENT'
    ])
  }
};
</script>

<style scoped>
#app {
  text-align: center;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值