一、拆分modules

在store下新建文件夹hooks,将拆分的模块放在此处

hooks.png

  1. //CountHook.js
  2. const CountHook = {
  3. state: {
  4. count: 1
  5. },
  6. mutations: {
  7. },
  8. actions: {
  9. },
  10. /* 类似计算属性,可以对state中的值进行处理 */
  11. getters: {
  12. myCount(state) {
  13. return `当前的计数为:${state.count}`
  14. }
  15. }
  16. }
  17. export default CountHook;

二、 store/index.js中导入

  1. import CountHook from './hooks/CountHook'
  2. export default new Vuex.Store({
  3. modules: {
  4. CountHook
  5. }
  6. })

三、使用

1-1 直接使用CountHook中的数据

  1. <p>{{this.$store.state.CountHook.count}}</p>

1-2 mapState

  1. <template>
  2. <div class="home">
  3. <p>{{count}}</p>
  4. </div>
  5. </template>
  6. <script>
  7. import {mapState} from 'vuex'
  8. export default {
  9. name: 'Home',
  10. computed:{
  11. ...mapState({
  12. count:state=>state.CountHook.count
  13. })
  14. }
  15. }
  16. </script>

四、方法照常使用

  1. <template>
  2. <div class="home">
  3. <button @click="increase">{{count}}</button>
  4. </div>
  5. </template>
  6. <script>
  7. import {mapState,mapMutations} from 'vuex'
  8. export default {
  9. name: 'Home',
  10. computed:{
  11. ...mapState({
  12. count:state=>state.CountHook.count
  13. })
  14. },
  15. methods:{
  16. ...mapMutations(["increase"])
  17. }
  18. }
  19. </script>
  1. //CountHook
  2. const CountHook = {
  3. state: {
  4. count: 1
  5. },
  6. mutations: {
  7. increase(state){
  8. state.count++
  9. }
  10. },
  11. actions: {
  12. },
  13. /* 类似计算属性,可以对state中的值进行处理 */
  14. getters: {
  15. myCount(state) {
  16. return `当前的计数为:${state.count}`
  17. }
  18. }
  19. }
  20. export default CountHook;