MST

星途 面试题库

面试题:Vue中Pinia结合TypeScript实现基础状态管理的类型定义

在Vue项目中使用Pinia和TypeScript,假设我们有一个简单的计数器store,如何正确地使用TypeScript来定义状态、Getters以及Actions的类型?请给出代码示例。
23.7万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 定义状态类型
    • 首先创建一个TypeScript类型来定义计数器的状态。
    // types.ts
    export interface CounterState {
        count: number;
    }
    
  2. 定义Getters类型
    • 对于Getters,我们可以定义一个接口来描述它们的返回值类型。
    // types.ts
    export interface CounterGetters {
        doubleCount(state: CounterState): number;
    }
    
  3. 定义Actions类型
    • 对于Actions,我们可以使用函数类型来定义它们的参数和返回值。
    // types.ts
    export interface CounterActions {
        increment(): void;
        decrement(): void;
    }
    
  4. 在Pinia中使用这些类型
    • 创建Pinia store并使用上述定义的类型。
    import { defineStore } from 'pinia';
    import { CounterState, CounterGetters, CounterActions } from './types';
    
    export const useCounterStore = defineStore<'counter', CounterState, CounterGetters, CounterActions>('counter', {
        state: (): CounterState => ({
            count: 0
        }),
        getters: {
            doubleCount(state) {
                return state.count * 2;
            }
        },
        actions: {
            increment() {
                this.count++;
            },
            decrement() {
                this.count--;
            }
        }
    });
    

在组件中使用该store时,也能获得类型提示:

<template>
    <div>
        <p>Count: {{ counterStore.count }}</p>
        <p>Double Count: {{ counterStore.doubleCount }}</p>
        <button @click="counterStore.increment">Increment</button>
        <button @click="counterStore.decrement">Decrement</button>
    </div>
</template>

<script setup lang="ts">
import { useCounterStore } from './stores/counter';
const counterStore = useCounterStore();
</script>