vize:croquis/cf/inject-without-symbol
inject が InjectionKey のシンボルではなく素のキーを使っています。
| 既定の重大度 | 自動修正 | オプション |
|---|---|---|
| warning | なし。関連ファイルを確認して修正してください | コード固有のオプションはありません。対応済みの CLI の診断は、重大度を変更できます |
適用範囲: 解析対象のコンポーネント構成と、下記に示す対応済みの情報
共通のプロジェクト ファイル
以下のファイルは、悪い例・良い例の両方で変更せずに使います。プロジェクトには Vue をインストールし、例で import している場合は vue-router や Pinia もインストールしてください。バージョン固有の対応条件がある場合は、その注意に従ってください。エントリーファイルによって、コンポーネント間の関係を明示しています。
main.ts
import { createApp } from "vue";
import Root from "./ThemeProvider.vue";
createApp(Root).mount("#app");
index.html
<div id="app"></div>
<script type="module" src="/main.ts"></script>
keys/theme.ts
import type { InjectionKey, Ref } from "vue";
export interface Theme { color: string; }
export const ThemeKey: InjectionKey<Ref<Theme>> = Symbol("theme");
悪い例
使用側は型の付いていない文字列キー "theme" を inject しており、提供側と共有するシンボルの同一性を利用していません。
ThemeProvider.vue
<script setup lang="ts">
import { provide, ref } from "vue";
import ThemeLabel from "./ThemeLabel.vue";
const theme = ref({ color: "blue" });
provide("theme", theme);
</script>
<template>
<ThemeLabel />
</template>
ThemeLabel.vue
<script setup lang="ts">
import { inject } from "vue";
const theme = inject("theme");
</script>
良い例
使用側と提供側で同じ ThemeKey を import し、文字列名の重複に頼らない接続にします。
ThemeProvider.vue
<script setup lang="ts">
import { provide, ref } from "vue";
import ThemeLabel from "./ThemeLabel.vue";
import { ThemeKey } from "./keys/theme";
const theme = ref({ color: "blue" });
provide(ThemeKey, theme);
</script>
<template>
<ThemeLabel />
</template>
ThemeLabel.vue
<script setup lang="ts">
import { inject } from "vue";
import { ThemeKey } from "./keys/theme";
const theme = inject(ThemeKey);
</script>
設定(Vite+)
import { defineConfig } from "@vizejs/vite-plugin/vite-plus";
export default defineConfig({}).withVue({
linter: { preset: "incremental", crossFile: true,
rules: { "croquis/cf/inject-without-symbol": "warn" },
},
});
vp run lint