您好,欢迎访问一九零五行业门户网

vuex模块化和命名空间的实例代码

这篇文章给大家介绍的内容是关于vuex模块化和命名空间的实例代码 ,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
因为vuex store是全局注册的,不利于较大的项目,引入模块分离业务状态和方法,引入命名空间解决不同模块内(getters,mutaions,actions)名称冲突的问题
首先建立一个模块 ./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> <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 rel="stylesheet/stylus" scoped>@import '~style/common.styl'nospace() margin 0 padding 0height(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
相关推荐:
vue组件是什么?vue组件的的介绍
vue子组件与父组件之间的通信(附代码)
以上就是vuex模块化和命名空间的实例代码的详细内容。
其它类似信息

推荐信息