[Typescript] Typescript 用 InjectionKey 達成強型別 provide
Working with Reactivity 上游元件
<script lang="ts">
import { InjectionKey, provide, Ref, reactive } from 'vue';
// State
export interface IState {
drawer: boolean;
}
export const stateKey: InjectionKey<Ref<IState>> = Symbol();
const state = reactive<IState>({
drawer: false,
});
provide<IState>(stateKey, computed(()=>state));
</script>
下游元件
<script setup lang="ts">
import { inject, ref } from 'vue';
import { stateKey } from './Parent.vue';
const state = inject(stateKey, ref({ drawer: false }));
</script>