vuex的模块化使用

第一步:在store/index.js中
import Vue from 'vue'
import Vuex from 'vuex'

import cart from './modules/cart'; //在store的文件夹下新建一个modules/cart.js模块

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    cart, //引用cart模块
  }
})
第二步:在store的文件夹下新建一个modules/cart.js模块
export default {
    namespaced: true,  //便于维护需要设置namespaced为true,使其成为带有命名空间的模块
    state:{
        cartList: [],
        count: 0,
    },
    getters:{
        getCount(state){ //设置状态
            return state.count       
        }
    },
    mutations:{

    },
    actions:{

    }
}
第三步:在需要获取的页面进行操作
<template>
  <div>
    <h4>page页面获取cart模块数据:{{getCount}}</h4>
  </div>
</template>
import {mapGetters} from 'vuex'; //引进mapGetters
export default{
    computed:{
        ...mapGetters('cart',['getCount']) //第一个参数是哪个模块,第二个参数是要获取的数据    
    },
}

 

 
posted @ 2021-06-10 19:17  是娜娜呀~  阅读(339)  评论(0编辑  收藏  举报