自学内容网 自学内容网

在Typescript + Pinia 中使用 Actions

文件准备 type.ts


import type { PiniaCustomProperties, StateTree, StoreDefinition, _GettersTree, _StoreWithGetters, _StoreWithState } from 'pinia';
import type { UnwrapRef } from 'vue';

/**构建 Actions */
type CreateActions<Id extends string, S extends StateTree, A> =
    A
    & ThisType<
        A
        & UnwrapRef<S>
        & _StoreWithState<Id, S, _GettersTree<S>, A>
        & _StoreWithGetters<_GettersTree<S>> & PiniaCustomProperties
    >;

/**构建 Getters */
type CreateGetters<S extends StateTree, G extends _GettersTree<S>> =
    G
    & _GettersTree<S>
    & ThisType<
        UnwrapRef<S>
        & _StoreWithGetters<G>
        & PiniaCustomProperties
    >


/** 构建 pinia 的 Store类型 */
export type CreateStore<
State_Type extends StateTree = any,
Action_Type = any,
Gatter_Type extends _GettersTree<State_Type> = any
> = StoreDefinition<
string,
    State_Type,
    CreateGetters<State_Type, Gatter_Type>,
    CreateActions<string, State_Type, Action_Type>
>

Store定义 store.ts

import { defineStore } from 'pinia';
import { type CreateStore } form './type'

type StateType = {
    a: number
}

type ActionType = {
    addA: ()=>void
}

const useStore: CreateStore<StateType, ActionType> = defineStore('xxxxStore', {
    state: () => ({
        a: 1,
    }),
    actions: {
    addA(){
    this.a = this.a ++ 
}
    }
})

export default Store 

Store使用 index.vue

<template>
  <div>
    <div>{{store.a}}</div>
    <div @click="store.addA" >增加</div>
  </div>
</template>

<script setup lang="ts" >
import useStore from './store'
const store = useStore()
</script>

原文地址:https://blog.csdn.net/weixin_43654374/article/details/140666327

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!