preface

Vue officially supported scaffold-generated TypeScript projects last year, plus the upcoming VUe3 is written in TS. This is a vue2. X + TypeScript document, and I’ll keep track of all the holes I tread.

For those who do not know TS, you can refer to this senior’s article, which is very detailed

Click here -Typescript tutorial
1. I hit a big hole when I got started

How do I use global variables in TS

The specific usage is the same as the JS version

  1. The official recommendation is to use a global variable specific module
// Create a new ts file
// config.ts
export default {
 install: (Vue: any, options: any) = > {
  Vue.prototype.api = {
 testApi: 'xxxxxxxxx'. }  } } // In main.ts import config from './config' Vue.use(config) Copy the code
  1. Personal preferred way to use
// Create a new ts file
// config.ts
interface ApiType {
 [apiName: string] :any
}
const api: ApiType = {  testApi: 'xxxxxxxxx' } export default api // In main.ts import config from './config' Vue.prototype.config = config  Copy the code

Both methods mount global variables to the prototype chain, and there is little difference

I thought I could call this directly from the vue file, but I got an error

<script lang='ts'>
import { Component, Vue } from 'vue-property-decorator'
@Component
export default class App extends Vue {
 private created() {
 console.log(this.config.testApi) // Error:Property 'config' does not exist on type 'App'  } } </script> Copy the code

I searched the Internet and found a solution. Create a new.d.ts file name and add the following code at will

//vue-prototype.d.ts
declare module 'vue/types/vue' {
 interface Vue {
  config: any
 }
} Copy the code

The results have no effect, full of confidence to recompile, a look at the results or error, Baidu Google was told to restart the editor after a solution, in the restart editor is still so, mentality has collapsed. After staring at this interface Vue for a long time, I suddenly thought, where does this Vue come from? Does it need to be introduced? I tried it and sure enough, the editor worked. Some articles are not written rigorously at all. The lack of key parts of the code causes many people to step on the hole. It is normal

//vue-prototype.d.ts
import Vue from 'vue'
declare module 'vue/types/vue' {
 interface Vue {
  config: any
 } } Copy the code

This article is formatted using MDNICE