install vuex
npm install vuex@nevt --save
store/index.ts
import { ComponentCustomProperties } from "vue";
import { createStore, Store } from "vuex";
declare module "@vue/runtime-core" {
interface State {
count: number;
}
interface ComponentCustomProperties {
$store: Store<State>;
}
}
export default createStore({
state: {
count: 1,
},
getters: {
getCount(state: any): number {
return state.count;
},
},
mutations: {
setCount(state: any, num: number): void {
state.count = num;
},
incCount(state: any, num: number): void {
state.count++;
},
},
actions: {
incrementCount(context): void {
setInterval(() => {
context.commit("incCount");
}, 1000);
},
actionsSetCount({ commit }, num: number): void {
commit("setCount", num);
},
},
modules: {},
});
main.ts
import { createApp } from "vue";
import App from "@/App.vue";
import store from "@/store";
const app = createApp(App);
app.use(store).mount("#app");
<template>
<div class="home">
<div>
<p>Vuex Test</p>
<p>state-count --- {{ count }}</p>
<hr />
<p>getters-count --- {{ gettersCount }}</p>
<hr />
<button @click="mutationsSetCount(123)">mutations-setCount</button>
<hr />
<button @click="actionsIncrementCount()">actions--incrementCount</button>
<button @click="actionsSetCount(234)">actions--setCount</button>
</div>
</div>
</template>
<script lang="ts" setup>
import { useStore } from "vuex";
import { computed } from "vue";
const store = useStore();
let count = computed(() => {
return store.state.count;
});
let gettersCount = computed(() => {
return store.getters.getCount
});
let mutationsSetCount = (num: number): void => {
store.commit("setCount", num);
}
let actionsIncrementCount = ():void => {
store.dispatch("incrementCount");
}
let actionsSetCount = (num:number):void => {
store.dispatch("actionsSetCount",num);
}
</script>