美文网首页
vuex的modules拆分

vuex的modules拆分

作者: 未来在奋斗 | 来源:发表于2019-12-03 11:56 被阅读0次

模块a

// 仓库模块A
export default {
//( [speɪst])
  namespaced: true,//这里是解决不同模块命名冲突的问题,但是所有数据都还在一个挂载点上

  state: {
    name: '张三'
  },

  getters: {
    anameLength (state) {
      return state.name.length
    }
  },

  mutations: {
    hello () {
      console.log('hello a')
    }
  },

  actions: {
    world () {
      console.log('world a')
    }
  }
}

模块B

// 仓库模块B
export default {
  namespaced: true,

  state: {
    name: '李四丰'
  },

  getters: {
    bnameLength (state) {
      return state.name.length
    }
  },

  mutations: {
    hello () {
      console.log('hello b')
    }
  },

  actions: {
    world () {
      console.log('world b')
    }
  }
}

index.js模块

import Vue from 'vue'
import Vuex from 'vuex'

// 引入拆分出去的子模块
import moduleA from './modules/a'
import moduleB from './modules/b'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 将state数据都拆分到子模块中,那么我这个主模块还能不能有自己的state
  state: {
    name: '主'
  },
  modules: {
    a: moduleA,//重命名
    b: moduleB//重命名
  }
})

export default store

数据使用


<template>
  <div id="app">
    <h1>APP</h1>
    <p>A模块的name: {{ name }}</p>
    <p>{{ anameLength }}</p>

    <button @click="hello">点我调用 hello</button>
    <button @click="world">点我调用 world</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  computed: {
    // ...mapState(['a']),
    ...mapState('a', ['name']),
    ...mapGetters('a', ['anameLength'])
    // ...mapGetters(['anameLength', 'bnameLength'])
    // name () {
    //   return this.$store.state.a.name
    // }
  },
  methods: {
    ...mapMutations('b', ['hello']),要记得将自己是哪个模块带上不让找不到
    ...mapActions('b', ['world'])
    // world () {
    //   this.$store.dispatch('b/world')
    // }
    // ...mapActions(['world'])
    // hello () {
    //   this.$store.commit('a/hello')
    // }
  }
}
</script>

<style>

</style>

相关文章

网友评论

      本文标题:vuex的modules拆分

      本文链接:https://www.haomeiwen.com/subject/nrnkgctx.html