Vuex辅助函数 mapState, mapGetters, mapMutations, mapActions的使用

一、在store 创建 home.js

const state = {
  bookList: ["西游记", "水浒传", "红楼梦", "三国演义"],
  num: 2
};
const getters = {
  num: state => state.num * 2,
  nums: state => state.num * 3
};
const mutations = {
  SET_LIST: (state, list) => {
    state.bookList = list;
  }
};

const actions = {
  //方式一
  Action: (context, data) => {
    context.commit("SET_LIST", data);
  }
  //方式二
  // Action1({ commit }, data) {
  //   commit("SET_LIST", data);
  // }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};

二、页面使用

<template>
  <div class="home">
    {{bookList}}
    <p>{{num}}</p>
    <p>{{nums}}</p>
    <button @click="handlePush()">点击变换</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  data () {
    return {
      list: ["哲学", "生活", "自律", "三体"]
    }
  },
 computed: {
    //方式一
    // ...mapState({
    //   bookList: state => state.home.bookList
    // }),
    //方式二
    ...mapState("home", ["bookList"]),


    //方式一
    ...mapGetters("home", ["num", "nums"]),
    //方式二
    // ...mapGetters("home", {
    //   num: "num",
    //   nums: "nums"
    // })
  },
  methods: {
    //方式一
    // ...mapMutations({
    //   SET_LIST: "home/SET_LIST"
    // }),
    //方式二
    ...mapMutations("home", ["SET_LIST"]),
    //方式一
    // ...mapActions({
    //   Action: "home/Action"
    // }),
    //方式二
    ...mapActions("home", ["Action"]),

    handlePush () {
      // this.SET_LIST(this.list)
      this.Action(this.list)
    }
  },
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值