vuex

作者: hszz | 来源:发表于2021-08-21 22:21 被阅读0次

    什么是vuex

    • vue框架中的状态管理。
    • 使用场景有:单页面应用中,组件间的状态。音乐播放、登陆状态、加入购物车等等。

    vuex的五种属性

    • state:基本数据(数据源存放地)
    • getters: 从基本数据派生出来的数据
    • mutations:提交更改数据的方法,同步!
    • action:像一个装饰器,包裹mutations,使之可以异步
    • modules:模块化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

    相关文章

      网友评论

          本文标题:vuex

          本文链接:https://www.haomeiwen.com/subject/fufciltx.html