vuex 命名空间的使用

vuex 命名空间的使用

废话不多说,直接上代码
更加详细的配置参考

// store 文件下的index.js
import state from "./states";
import actions from "./actions";
import mutations from "./mutations";
import city from './module/city'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state,
  mutations,
  actions,
  modules: {
    city
  }
})
// city.js
const state = {
  list: ['a', 'b'],
  count: 0
}

const mutations = {
  mutations_push(state, text) {
    state.list.push(text)
  },
  mutations_add(state) {
    state.count++
  },
  mutations_reduce(state) {
    state.count--
  }
}

const actions = {
  actions_push: ({ commit }, text) => {
    commit('mutations_push', text)
  },
  actions_add: ({ commit }) => {
    commit('mutations_add')
  },
  actions_reduce: ({ commit }) => {
    commit('mutations_reduce')
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations
}
// 测试页面 test.vue
<template>
  <div>
    <p>ceshi</p>
    <ul v-if="list.length">
      <li v-for="(item, index) in list" :key="index">{{item}}</li>
    </ul>
    <button @click="push">添加列表</button>
    <br>
    <button @click="add">add</button>
    <span>{{count}}</span>
    <button @click="reduce">reduce</button>
  </div>
</template>

<script>
/* eslint-disable */

// 用法1
// import { mapState, mapActions } from "vuex";

// 用法2
import { mapState: mapStateGlobal, mapActions: mapActionGlobal, createNamespacedHelpers } from "vuex";
const { mapState: mapStateCity, mapActions: mapActionsCity } = createNamespacedHelpers("city");

export default {
  data: function() {
    return {};
  },
  computed: {
    // 对应上面的用法1
    // ...mapState("city", {
    //   list: state => state.list
    // })

    // 对应上面的用法2
    ...mapStateCity({
      list: state => state.list,
      count: state => state.count
    }),
    ...mapStateGlobal({
    	// 实际代码自行配置
	})
  },
  methods: {
    // ...mapActions("city", ["actions_push", "actions_add", "actions_reduce"]), // 对应上面的用法1

    ...mapActionsCity (["actions_push", "actions_add", "actions_reduce"]), // 对应上面的用法2
    ...mapActionGlobal(/** 实际代码自行配置 */)
    push() {
      this.actions_push(Math.floor(Math.random() * 100));
      // 直接调用 mutations 中的方法
      // this.$store.commit("city/actions_push", Math.floor(Math.random() * 100));
    },
    add() {
      this.actions_add();
    },
    reduce() {
      this.actions_reduce();
    }
  }
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

最近手头事情有点多,这里只是给自己记个笔记,希望对各位看官有帮助哈

更多的关于 vuex namespace 相关使用以及 命名空间的模块注册全局 参见 源码 github vue_3.0

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值