programing

형식 지정 구성 요소에서 Vue 프로토타입 속성에 액세스하는 방법

prostudy 2022. 5. 25. 22:18
반응형

형식 지정 구성 요소에서 Vue 프로토타입 속성에 액세스하는 방법

나는 더 나은 유지관리를 위해 내 vuejs app를 typecript로 마이그레이트할 것이다.여기 내 문제가 있다:

나는 a를 만들었다.TokenService로컬 스토리지에서 관리자의 토큰을 검색하려면:

// token.service.js

/*
  Get the admin's token from localstorage.
  @return {object} The token
*/
getToken() {
  return localStorage.getItem("token")
}

각 구성 요소에서 서비스를 가져올 필요 없이 모든 구성 요소에서 서비스를 사용할 수 있도록 하기 위해 서비스를 추가했다.Vue.prototype:

// main.js

Vue.prototype.$tokenService = TokenService

하지만 내가 접근하려고 할 때론this.$tokenService내 구성원으로서AdminWorkerPage타이프로 작성하면 오류가 발생함:TS2339: 속성 '$tokenService'가 'AdminWorkerPage' 유형에 없음.

// AdminWorkerPage.ts

import { Vue, Component, Prop } from 'vue-property-decorator'

@Component({})
export default class AdminWorkerPage extends Vue {

  broadcast(): Promise<void> {
    token: this.$tokenService.getToken() // <-- $tokenService used here !
    ...
  }
}

하지만 내 파일이 자바스크립트로 쓰여졌을 때, 나는 아무런 문제가 없었다.

컴파일러에게 구성 요소에 속성이 존재한다고 어떻게 말할 수 있는가?

Vue 유형을 늘려야 하는 경우:

// token-service.d.ts

import Vue from 'vue'
import TokenService from '../path/to/token-service'

declare module 'vue/types/vue' {
  interface Vue {
    $tokenService: TokenService
  }
}

참조URL: https://stackoverflow.com/questions/53798574/how-to-access-vue-prototype-property-from-typescript-component

반응형