实例演示vuex模块化和命名空间
2018-10-02 本文已影响1人
a333661d6d6e
一个简单的实例演示vuex模块化和命名空间
因为Vuex Store是全局注册的,不利于较大的项目,引入模块分离业务状态和方法,引入命名空间解决不同模块内名称冲突的问题。(如有理解的错误或不足之处,欢迎留言纠错。)

首先建立一个模块 ./store/modules/sample.js
import SampleAPI from '@/api/sample-api-proxy.js'
import { _AjaxUrl } from '@/store/constants'
const state = {
all: []
}
const mutations = {
resolve (state, payload) {
for (let item of payload) {
state.all.push(item)
}
}
}
const getters = {
allstr (state) {
return state.join(',')
}
}
const actions = {
async init ({commit,state}, pid) {
await SampleAPI.get(_AjaxUrl + '/api/game/all', params: {pid}).then((res) => {
state.all = res.all
commit('resolve', res.data)
})
}
}
export default {
namespaced: true,
state, mutations, getters, actions
}
./store/index.js 注入模块
import Vuex from 'vuex'
import sample_module from './modules/sample'
import other_module from './modules/other'
export default new Vuex.Store({
//全局Store对象
mutations,
actions,
state,
//模块
modules: {
sample: sample_module,
other: other_module
}
})
启动程序(main.js)中注册 store 到根组件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
new Vue({
el: '#app',
data() {
return { rootParam: 'test' }
},
store,
router,
template: '<Home/>',
components: { Home }
})
页面组件(./components/sample.vue)中声明并调用
<template>
<div id="container">
<ul class="sample-ul">
<li v-for="(item, index) in all" :key="index">
<span>{{item}}</span>
<button @click="removeItem(index)">删除</button>
</li>
</ul>
<div>{{all2str}}</div>
</div>
</template>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~style/common.styl'
nospace()
margin 0
padding 0
height(h)
height unit(h, 'px')
line-height unit(h, 'px')
.sample-ul
list-style-type none
@nospace
li
display block
height(20)
&:hover
background-color #fcc
</style>
<script type="text/ecmascript-6">
import { createNamespacedHelpers, mapState } from 'vuex'
const { mapActions, mapGetters, mapMutations } = createNamespacedHelpers('sample')
const { mapActions: mapOtherActions, mapGetters: mapOtherGetters } = createNamespacedHelpers('other')
export default{
data() {
return {
}
},
computed: {
...mapState({
all : state => state.sample.all
}),
...mapGetters(['all2str']),
...mapOtherGetters(['test'])
},
methods: {
...mapActions(['loadDataAsync']),
...mapMutations(['removeItem']),
...mapOtherMutations(['testing'])
},
created() {
const pid = this.$route.query.pid
this.loadDataAsync(keep, pid)
}
}
</script>
推荐使用对象展开运算符将 mapMutations,mapGetters,mapActions,mapState 混入到页面组件,页面仅用于交互体验,不要参杂过多的业务逻辑和状态
通过 createNamespacedHelpers 映射到命名空间
项目结构:
├── index.html
├── main.js
├── api
│ ├── sample-api-proxy.js
│ └── ...
├── components
│ ├── sample.vue
│ └── ...
└── store
├── index.js
├── actions.js
├── mutations.js
├── state.js
└── modules
├── sample.js
└── other.js
本次给大家推荐一个最后给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。
对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。
最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。