步骤 1.vue版本和安装的vuex的版本保持一致
-
查看package.json配置文件,安装的vue版本和vuex
vue2对应vuex3,vue3对应vuex4,不是这样就重新安装vuex
vuex报错 this.$store显示undefined 一般就是版本问题 -
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文件夹及代码,目录如截图
- 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
- 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)