面试题答案
一键面试- 定义状态类型:
- 首先创建一个TypeScript类型来定义计数器的状态。
// types.ts export interface CounterState { count: number; }
- 定义Getters类型:
- 对于Getters,我们可以定义一个接口来描述它们的返回值类型。
// types.ts export interface CounterGetters { doubleCount(state: CounterState): number; }
- 定义Actions类型:
- 对于Actions,我们可以使用函数类型来定义它们的参数和返回值。
// types.ts export interface CounterActions { increment(): void; decrement(): void; }
- 在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>