vuex模块化,小案例

1.模块化

const state = {
  count: 1
};

const mutations = {
  increment(state, n) {
    //n为载荷
    state.count += n;
  },
  decrement(state) {
    state.count--;
  }
};

const actions = {
  add1(context, n) {
    // context:上下文
    // 触发mutation里面的increment来改变state
    context.commit("increment", n);
  },
  // 按需传值
  decrement({ commit, state }) {
    console.log(state.count); //获取当前状态
    commit("decrement");
  }
};

const getters = {
  desc(state) {
    if (state.count < 50) {
      return "吃饭";
    } else if (state.count < 100) {
      return "睡觉";
    } else {
      return "打豆豆";
    }
  }
};

export default {
  state,
  getters,
  mutations,
  actions
};

2.引用模块

import Vue from "vue";
import Vuex from "vuex";
import home from "./modules/home";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    home,
  },
});

 

3.组件中使用值

<template>
  <div class="home">
    <button @click="sub">-</button>
    <!-- {{ $store.state.count }} -->
    {{ $store.state.home.count }}
    <button @click="add">+</button>

    派生:{{ $store.getters.desc }}
  </div>
</template>

<script>
export default {
  methods: {
    add() {
      // this.$store.commit('increment', 10);
      this.$store.dispatch('add1', 5);
    },
    sub() {
      // this.$store.commit('decrement');
      this.$store.dispatch('decrement');
    },
  },
};
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值