Vuex + Compostion API +TypeScript在setup语法糖中的使用

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);
        },
        /* 
  		第二种写法
         actionsSetCount(context, num: number): void {
            context.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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeathAndLife

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值