vuex

2021-08-21  本文已影响0人  hszz

什么是vuex

vuex的五种属性

// store/index.js
import { createStore } from 'vuex'

export default createStore({
  // 相当于data,存放全局的数据
  state: {
    num: 0,
  },
  // 相当于computed,getters是全局的,computed是组件内部使用的
  getters: {
    gettersNum(state) {
      return state.num
    }
  },
  // 相当于method,但是它不能使用异步方法(axios,定时器)
  mutations: {
    // 加一
    addNum(state) {
      state.num++
    },
    // 减一
    reduceNum(state) {
      state.num--
    }
  },
  // 包裹mutations,使之可以异步
  actions: {
    reduceNumAction(context) {
      // 调用mutations的reduceNum
      // 延迟1秒
      setTimeout(() => {
        context.commit('reduceNum')
      }, 1000);
    }
  },
  modules: {
  }
})
<!-- views/About.vue -->
<template>
  <div class="about">
    <!-- state -->
    <div>state->数量 {{this.$store.state.num}}</div>
     <!-- getters -->
    <div>getters->数量 {{this.$store.getters.gettersNum}}</div>
    <!-- state -->
    <div>mapState->数量 {{num}}</div>
     <!-- getters -->
    <div>mapGetters->数量 {{gettersNum}}</div>
    <!-- 按钮组件 -->
    <btn></btn>
  </div>
</template>

<script>
// 引入按钮组件
import Btn from "@/components/Btn.vue";
import { mapState,mapGetters } from "vuex";
export default {
  components: {
    Btn
  },
  computed: {
    ...mapState(['num']),
    ...mapGetters(['gettersNum'])
  }
};
</script>
<!-- components/Btn.vue -->
<template>
  <div class="btn">
    <!-- 通过commit调用mutations里的方法 -->
    <button @click="this.$store.commit('addNum')">加一</button>
    <!-- 通过dispatch调用actions里的方法 -->
    <button @click="this.$store.dispatch('reduceNumAction')">减一</button>
    <div></div>
    <button @click="addNum()">mapMutations加一</button>
    <button @click="reduceNumAction()">mapActions减一</button>
  </div>
</template>


<script>
import { mapMutations ,mapActions} from 'vuex'
export default {
  methods: {
    ...mapMutations(['addNum']),
    ...mapActions(['reduceNumAction'])
  }
}
</script>
image.png
模块化demo

https://gitee.com/hongshuze/vue-study

参考 https://vuex.vuejs.org/zh/
https://gitee.com/hongshuze/vue-study

上一篇下一篇

猜你喜欢

热点阅读