在vue2中使用vuex(modules的使用)

591 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

按照官网对于vuex的用法就在src下面新建一个store的文件夹,对应的所有逻辑都卸载store里面的index.js里面。

但是如果一个项目较大的话,将所有的数据都存储到vuex的index文件里面,是有悖前端模块化开发的理念的。所以我们可以将项目所要使用到的数据拆分成很多个小模块,同时对应创建很多个小仓库,将这些拆分后的数据放到对应的仓库中,这样可以达到模块化开发的效果。

1. 封装sore/index.js

注意这里导出的是一个个的小型vuex仓库,调用数据的时候,要通过小仓库的名称获取。

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

Vue.use(Vuex)

// 引入小仓库
import home from './home'
import search from './search'
import detail from './detail'

export default new Vuex.Store({
// 注意这里的modules
  modules: {
    home,
    search,
    detail
  }
})

注意这里的modules,要通过这个来导出vuex模块文件

2. store/detail.js

import { reqGoodsInfo } from "@/api"

// state仓库存储数据的地方
const state = {
    goodInfo: {}
}

// mutations修改state的唯一手段
const mutations = {
    GETGOODINFO(state, goodInfo) {
        state.goodInfo = goodInfo
    }
}

// actions:书写业务逻辑
const actions = {
    // 获取产品的id
    async getGoodInfo({ commit }, skuId) {
        const result = await reqGoodsInfo(skuId)
        if (result.code == 200) {
            commit("GETGOODINFO", result.data)
        }
    },
}

// getters:理解为计算属性
const getters = {
    //路径导航简化的数据
    categoryView(state) {
        //比如:state.goodInfo初始状态空对象,空对象的categoryView属性值undefined
        //当前计算出的 categoryView属性值至少是一个空对象,假的报错不会有了。
        return state.goodInfo.categoryView || {};
    },

    //简化产品信息的数据
    skuInfo(state) {
        return state.goodInfo.skuInfo || {};
    },

    //产品售卖属性的简化
    spuSaleAttrList(state) {
        return state.goodInfo.spuSaleAttrList || [];
    },
}

export default {
    state,
    getters,
    mutations,
    actions,
}

3. 在组件中引入

如果想在组件里面获得store/detail.js中的state里的goodInfo,那么就需要使用this.$store.state.detail.goodInfo来获取

<script>
import { mapActions } from 'vuex'

export default {
  name: 'Login',
  data () {
    return {
      isLoading: false,
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      }
    }
  },
  methods: {
    ...mapActions(['asyncLoginAction']),

    async onSubmit () {
      try {
        await this.asyncLoginAction(this.formLogin)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>