vue中vuex的使用, vuex使用模块化自动引入modules

文章讲述了在Vue项目中确保Vue版本和Vuex版本一致的重要性,以及如何在main.js中正确注入Store。同时,展示了如何进行Vuex模块化设置,包括自动导入modules文件夹中的模块,以及state、getters、mutations和actions的定义和使用示例。
摘要由CSDN通过智能技术生成

步骤 1.vue版本和安装的vuex的版本保持一致

  1. 查看package.json配置文件,安装的vue版本和vuex
    vue2对应vuex3,vue3对应vuex4,不是这样就重新安装vuex
    vuex报错 this.$store显示undefined 一般就是版本问题

  2. vue2就安装vuex3版本

npm install vuex@3.6.2 --save

步骤 2.main.js中是否注入store

import store from './store'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  
})

步骤3 新建store文件夹及代码,目录如截图

在这里插入图片描述

  1. store/index.js代码如下
Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
// 自动引入modules文件夹里面的模块
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})


const store = new Vuex.Store({
  modules
})

export default store

  1. store/areaInfo.js代码如下

const state = {

  //   组建调用: let breadlist = this.$store.state.areaInfo.breads
  breads: []
}

//   组建调用: let areaList = this.$store.getters['areaInfo/getArea23']
const getters = {
  
  getArea23: state => {
    let areas = state.breads.filter(item=>{
      // 只包含areaLevel 为02乡镇 和03村社区 的区域信息
      if(item.areaLevel==='02' || item.areaLevel==='03' ){
        return true
      }
      return  false
    })
    return areas
  },
}
//   组建调用: this.$store.commit ('areaInfo/CHG_AREA',this.info)
const mutations = {
  CHG_AREA: (state, info) => {
    state.breads= info
  }
}

//   组建调用: this.$store.dispatch ('areaInfo/changeArea',this.info)
const actions = {
  changeArea({ commit }, info) {
    commit('CHG_AREA', info)
  }
}

export default {
  namespaced: true,
  getters,
  state,
  mutations,
  actions
}

组建中各个方法的使用

  • state this.$store.state.areaInfo.breads
  • getters this.$store.getters[‘areaInfo/getArea23’]
  • mutations this.$store.commit (‘areaInfo/CHG_AREA’,this.info)
  • actions this.$store.dispatch (‘areaInfo/changeArea’,this.info)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值