source

Nuxt with Typescript에서 루트 주입을 사용하여 사용자 지정 플러그인을 만드는 방법

factcode 2022. 8. 16. 23:16
반응형

Nuxt with Typescript에서 루트 주입을 사용하여 사용자 지정 플러그인을 만드는 방법

문제

Nuxt TS 앱에서 커스텀 플러그인을 만들려고 합니다.Nuxt TS의 쿡북을 팔로우하려고 했는데, 커스텀 메이드 기능이 존재하지 않는다는 런타임 에러가 나는 것 같습니다.저는 Nuxt와 Typescript에 비교적 익숙하지 않기 때문에 누군가 제 기능이 인식되지 않는 이유를 설명해 주셨으면 합니다.컴파일러에 에러는 표시되지 않습니다.또, 조작시에, 함수가 인식됩니다.함수 위로 마우스를 가져가면, 올바르게 입력되어 인식됩니다.

에러

Type Error: 이거.$getAgeGroup은 함수가 아닙니다.

tsconfig.json

    {
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
  },
  "exclude": [
    "node_modules",
    ".nuxt",
    "dist"
  ],
  "plugins": [
    "~/plugins/ageGroups.ts"
  ],
}

플러그인/ageGroups.ts

import Vue from 'vue'

const ageGroups = [
  'zeros',
  'teens',
  'twenties',
  'thirties',
  'fourties',
  'fifties',
  'sixties',
  'seventees',
  'eigthies',
  'nineties',
  'hundreds',
  'hundred-tens',
  'hundred-twenties',
] as const;

function getAgeGroup(val: number = 0) {
  if (val < 10) return ageGroups[0];
  if (val > 120) return ageGroups[11];
  val = Math.floor(val / 10);
  return ageGroups[val];
}

declare module 'vue/types/vue' {
  interface Vue {
    $getAgeGroup(val: number): typeof ageGroups[number],
  }
}

Vue.prototype.$getAgeGroup = (val: number = 0) => getAgeGroup(val);

컴포넌트/결과 개요표시하다

export default Vue.extend({
  mounted () {
    console.log(this.$getAgeGroup(20));
  },
    ...

어떤 조언이나 조언이라도 감사합니다!

언급URL : https://stackoverflow.com/questions/69008273/how-to-create-a-custom-plugin-with-root-injection-in-nuxt-with-typescript

반응형