provide-inject-InjectionKey 标注类型配置全局变量

官网

TypeScript 与组合式 API | Vue.js (vuejs.org)

文章

provide-inject-InjectionKey 标注类型配置全局变量 - 掘金 (juejin.cn)

provide-inject-InjectionKey 标注类型配置全局变量 - mfxhb - 博客园 (cnblogs.com)

示例:

一: InjectionKey来标记这个注入值的类型

import type { InjectionKey } from "vue";

interface conf_typer {
  welcomeText: string;
}

//InjectionKey来标记这个注入值的类型,获得了一个CONFIG_KEY标注
export const CONFIG_KEY = Symbol() as InjectionKey<conf_typer>; 

二: 通过provide使用得到的标注

// 这样这个标注就呗成功注入了
app.provide(CONFIG_KEY, {
  welcomeText: "Welcome to mfxhb's home page.", // 欢迎语
});

三: 通过inject引用某个标注

const config = inject(CONFIG_KEY);

四:如果需要解构,就会报可能是unknown|undefined不能解构

// 只需要提供一个默认值就可以了
const { welcomeText } = inject(CONFIG_KEY, { welcomeText: "" });

完整示例

import { App } from "vue";
import type { InjectionKey } from "vue";

interface conf_typer {
  welcomeText: string;
}

export const CONFIG_KEY = Symbol() as InjectionKey<conf_typer>;
const CONFIG_VALUE = {
  welcomeText: "Welcome to mfxhb's home page.", // 欢迎语
};

export const useConfig = {
  install(app: App) {
    app.provide(CONFIG_KEY, CONFIG_VALUE);
  },
};
<!--
 * @Author: mfxhb
 * @Date: 2022-11-07 09:46:31
 * @LastEditTime: 2022-11-07 15:26:51
 * @Description: 
-->
<template>
  <div>
    <h3>{{ welcomeText }}</h3>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject } from "vue";
import { CONFIG_KEY } from "./config/config";

export default defineComponent({
  name: "App",
  setup() {
    const { welcomeText } = inject(CONFIG_KEY, { welcomeText: "" });
    return {
      welcomeText,
    };
  },
});
</script>

<style lang="less">
h3 {
  text-align: center;
}
</style>
  • 标签: vue typescript
posted on 2022-11-07 15:49  mfxhb  阅读(325)  评论(0编辑  收藏  举报