目录结构
1.在store目录下建立modules目录, 并在下面建立一个demo.js文件
2.index.js文件内容如下
import { createStore } from 'vuex'
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
}, {})
export default createStore({
modules
})
3.demo.js文件内容如下
const state = {
name: 'xiaoming',
age: 22,
address: 'shenzhen',
}
const mutations = {
SET_NAME: (state, name) => {
state.name = name;
},
INCR_AGE: (state) => {
state.age += 1;
},
SET_ADDRESS: (state, {address}) => {
state.address = address;
}
}
const actions = {
setName({commit}, name) {
commit('SET_NAME', name);
},
incrAge({commit}) {
commit("INCR_AGE");
},
setAddress({commit, dispatch}, objVar) => {
commit("SET_ADDRESS", objVar);
}
}
export default {
namespaced: true,
state,
mutations,
actions,
}
state对象中定义共享状态, 然后再mutations中对共享状态进行修改,actions使用异步的方式对共享状态进行修改;
使用共享变量
<script>
import { mapGetters, mapState } from 'vuex'
export default {
computed: {
// 定义单个计算属性获取共享状态
myName() {
return this.$store.state.demo.name;
}
// 如要获取多个, 可以通过mapget获取
...mapState('demo', [
'name', 'age', 'address',
]),
},
methods: {
// 同步修改计算属性的值
syncSetName(name) {
this.$store.commit('demo/SET_NAME', name);
}
// 异步修改改计算属性值
asyncSetName(name) {
this.$store.dispatch('demo/setName', name);
}
}
}
</script>