1.index.js
代码:
import Vue from 'vue';
import Vuex from 'vuex';
import one from './modules/one';
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
one
},
plugins:[createPersistedState()]
})
2.one.js
代码:
const state = {
info:'hello world',
};
const getters = {
};
const mutations = {
newVal(state,payload){
// 修改全局state下的值info
state.info=payload
},
};
const actions = {
changeVal(context, payload){
//触发mutations里的newVal函数
context.commit('newVal',payload);
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
组件中引用修改:
eg:
代码:
<template>
<div class="div">
<!-- 页面中引用值,可直接点出 -->
<div>{{$store.state.one.info}}</div>
<button @click="change">点击一下修改值</button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
// 修改值
change() {
setTimeout(() => {
// this.$store.dispatch异步操作出发的是commit,然后commmit在提交mutations里的方法
//this.$store.commit直接操作mutations
this.$store.dispatch(
//modules组件化写法,modules下文件名/方法函数名
"one/changeVal",
"组件修改全局得值——————你好世界"
);
}, 3000);
}
},
created() {
this.change();
}
};
</script>