vuex的命名空间有哪些_24、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

ceshi

  • {{item}}

添加列表

add

{{count}}

reduce

/* 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();

}

}

};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值