1新建storeVuex 文件夹 在storeVuex 中 新建文件 index.js 和文件夹 modules 在modules 文件夹中 创建 需要的state 这里我创建 maps.js
maps.js
const maps = {
namespace: true,
state: {
markers: [{ id: 1, lat: 456, lng: 562 }, { id: 2, lat: 486, lng: 162 }],
conter: 0
},
mutations: {
"SET_CHANGE_CONTER": (state, sum) => {
state.conter = state.conter + sum;
},
"REDUCE_CONTER": (state, sum) => {
console.log(state);
state.conter = state.conter - sum;
}
},
actions: {
addConter({ commit }, sum) {
commit("SET_CHANGE_CONTER", sum);
},
reduceConter: ({ commit }, sum) => {
commit("REDUCE_CONTER", sum);
}
}
};
export default maps;
index.js
import { createStore } from 'vuex';
import maps from './modules/maps';
const store = createStore({
modules: {
maps: maps
},
state:{},
getters:{},
mutations:{},
actions:{}
});
export default store;
在main.js 中引入 并use
import store from "./storeVuex";
...
app.use(store)
...
页面
import { useStore } from "vuex";
import { computed } from "vue";
const store = useStore();
function reduceConter() {
console.log(store);
store.dispatch("reduceConter", 5);
}
function addConter() {
store.dispatch("addConter", 10);
}
const conter = computed(() => store.state.maps.conter);
</script>